我有一个包含具有以下结构的嵌套对象的对象,我如何动态地将新项目 (newData
) 添加到 cost3
数组?
我试过了,但是没有推送新数据,我做错了什么?
const [file, setFile] = useState({})
setFile(file=> ({
...file,
[cost3]: {
...file.cost3,
newData
}
}))
文件
对象:
{
"info": {
},
"client": {
},
"costs": {
"cost1": 1,
"cost2": 5,
"cost3": [
{
"a": "test",
"b": "test",
"c": "test",
},
{
"d": "test",
"e": "test",
"f": "test",
},
//etc..
],
"cost4": [
{
"l": "test",
"n": "test",
"m": "test",
},
//etc..
]
}
}
最佳答案
const file = {
"info": {
},
"client": {
},
"costs": {
"cost1": 1,
"cost2": 5,
"cost3": [{
"a": "test",
"b": "test",
"c": "test",
},
{
"d": "test",
"e": "test",
"f": "test",
},
//etc..
],
"cost4": [{
"l": "test",
"n": "test",
"m": "test",
},
//etc..
]
}
}
const newData = { x: 'I am new' }
console.log(
{
...file,
costs: {
...file.costs,
cost3: [
...file.costs.cost3,
newData
]
}
}
)
关于javascript - 将项目推送到嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335534/