javascript - 向对象添加新数组
问题描述
我正在使用上下文 api 进行状态管理我为学生设置了初始状态:null 和标签:[] 学生是一个对象数组,其数据如下:
[
{
"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]
}
推荐阅读
- c++ - SFINAE 用于无符号类型选择
- java - 如何以编程方式将 Switch 添加到 PopupMenu(不使用 XML)?
- matplotlib - 在 tricontourf 中掩盖大量缺失的数据
- rust - 如何激活可选依赖项?
- swiftui - 在 Apple Watch 上的 SwiftUI 中,更新描述自具有 Always On 状态的日期以来的间隔的字符串的最佳方法是什么?
- html - 如何隐藏 HTML 元素中第 n 个分隔符之后的所有内容?
- c# - 需要有关 RuntimeBinderException 的帮助:无法对空引用执行运行时绑定
- amazon-web-services - ALB + Okta SSO 身份验证背后的 AWS 托管 ElasticSearch(现在称为 OpenSearch) - 不可能吗?
- r - 如何用 R 重新排列数据形状
- python - 如何使用 Python/Pandas 将非 CSV 文本文件转换为 CSV?