Reputation: 6896
I have an object with nested objects with the below structure, how can I dynamically add new items (newData
) to the cost3
array?
I have tried that but the new data isn't being pushed, what am I doing wrong?
const [file, setFile] = useState({})
setFile(file=> ({
...file,
[cost3]: {
...file.cost3,
newData
}
}))
File
object:
{
"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..
]
}
}
Upvotes: 3
Views: 137
Reputation: 8152
Replace [cost3]
with cost3
and {}
with []
, like so:
setFile(file=> ({
...file,
costs: {
...file.costs,
cost3: [
...file.costs.cost3,
newData
]
}
}))
Upvotes: 2
Reputation: 7949
You can try it using concat.
cost3 = [];
const [file, setFile] = useState({});
setFile(file => ({
cost3: file.cost3.concat(newData),
}));
Upvotes: 0
Reputation: 15
You can use .push()
method to add item to object, for dynamic addition you can iterate through the array.
Upvotes: -1
Reputation: 2391
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
]
}
}
)
Upvotes: 2