向对象添加新数组

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]
   }