Reputation: 21
I have a method in a component. I want to dynamically setState with a key in a nested array of objects.
method = (name, value) => {
console.log(name)
//a //value is 1
//b //value is 2
//c //value is 3
this.setState({ [name]:value })
}
when its not nested, it dynamically changes state successfully. However when its nested
method = (name, value) => {
this.setState({
ArrayOfObjects:[{
[name] : value
}]
}
My state becomes
state = {
ArrayOfObjects: [{
c: 3
}]
}
I want
state = {
ArrayOfObjects: [{
a: 1,
b: 2,
c: 3
}]
What's wrong?
Upvotes: 1
Views: 783
Reputation: 38777
Assuming that ArrayOfObjects
is an always an array with single object and that you want to merge name
/value
into that object:
method(name, value) {
// make a copy
const ArrayOfObjects = [...this.state.ArrayOfObjects];
// merge properties and set dynamic value
ArrayOfObjects[0] = { ...ArrayOfObjects[0], [name]: value };
this.setState({
ArrayOfObjects
});
}
Here is an example in action.
Hopefully that helps!
Upvotes: 0
Reputation: 6302
You could just push an element to the current ArrayOfObjects.
ArrayOfObjects = this.state.ArrayOfObjects;
ArrayOfObjects.push({[name] : value});
this.setState({
ArrayOfObjects
});
Or using the spread operator:
this.setState({
ArrayOfObjects: [
...this.state.ArrayOfObjects,
{[name] : value}
]
});
Upvotes: 1