我在下面有这个对象。我想知道如何选择特定项目并更新属性。例如。 Item 1 我想在数组中添加一个任务。
item: {
'item-1': {
id: 'item-1',
title: 'To do',
task: ['task-1', 'task-2', 'task-3', 'task-4']
},
'item-2': {
id: 'item-2',
title: 'In progress',
task: []
},
我现在有
const getItem = {...state.items['item-1']}
const newTaskList = [...getItem.task, newTask.id]
const newState = {
...state,
items: {
...state.items,
//How do I spread new array correctly in item 1?
//...state.items['item-1'].task
}
};
最佳答案
您需要使用对象键,即 item-1
并为其克隆属性,并为任务键添加新列表。简而言之,在覆盖要更新的键之前,您需要在对象的每个级别进行克隆
const newState = {
...state,
items: {
...state.items,
'item-1': {
...state.items['item-1'],
task: newTaskList
}
}
};
关于javascript - 如何在对象中传播嵌套属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833517/