繁体   English   中英

向对象添加新数组

[英]Add a new array to an object

我正在使用上下文 api 进行状态管理我已经为学生设置了一个初始状态:null 和标签:[] Students 是一个包含如下数据的对象数组:

[
{
 "id": 1,
 "city": "some city",
 "name" : "some name",
 "colors" : [
             "1": "blue",
             "2" : "red"
            ],
 "age": "some age"
},
{
 "id": 2,
 "city": "some city",
 "name" : "some name",
 "colors" : [
             "1": "green",
             "2" : "yellow"
            ],
 "age": "some age"
}
]

标签数组将是这样的

{
 "studentId": 1,
 "tag": "some tag",
},
{
 "studentId": 2,
 "tag": "some tag",
},
{
 "studentId": 2,
 "tag": "some tag",
},
]

现在我想将标签数组中的对象添加到学生数组中的匹配对象中。 例如,id 为 2 的学生,他有两个带有他 id 的标签。 我希望将带有 studentId 2 的标签数组作为数组添加到该特定 id 的学生对象中..不知道我是否有意义。

我的状态文件

 const addTag = async tag => {

    try {

        dispatch({ 
            type: ADD_TAG, 
            payload: tag
           })
    } catch (error) {
        dispatch({ 
            type: STUDENT_ERROR ,
            payload: error
           })
    }
}

我的减速机

 case ADD_TAG:
            return {
                ...state,
                
                tags: [...state.tags, action.payload],
 
            }

我只是填充标签状态..但我也想为学生状态这样做。 谢谢

你可以简单地复制学生数组(这样你就不会直接改变它),找到有问题的学生对象的索引,然后给它添加标签。

case ADD_TAG:
   let studentCopies = JSON.parse(JSON.stringify(state.students));
   let index = studentCopies.findIndex(s => s.id === action.payload.studentId);


   if (index > -1) {
      // if student object is in array, then add tag to student's tag array

     if (studentCopies[index].tags) {
       studentCopies[index].tags = [...studentCopies[index].tags, action.payload];
     } else {
        studentCopies[index].tags = [action.payload]
     }
   }  
    

   return {
     ...state,
     students: studentCopies,
     tags: [...state.tags, action.payload]
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM