我有一个带有以下结构的嵌套对象的对象,如何将新项目(newData
)动态添加到cost3
数组中?
我已经尝试过,但是没有推送新数据,我在做什么错了?
const [file, setFile] = useState({})
setFile(file=> ({
...file,
[cost3]: {
...file.cost3,
newData
}
}))
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..
]
}
}
答案 0 :(得分:2)
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
]
}
}
)
答案 1 :(得分:2)
将[cost3]
替换为cost3
,将{}
替换为[]
,就像这样:
setFile(file=> ({
...file,
costs: {
...file.costs,
cost3: [
...file.costs.cost3,
newData
]
}
}))
答案 2 :(得分:0)
您可以使用concat进行尝试。
cost3 = [];
const [file, setFile] = useState({});
setFile(file => ({
cost3: file.cost3.concat(newData),
}));
答案 3 :(得分:-1)
您可以使用.push()
方法向对象添加项目,要进行动态添加,可以遍历数组。