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?
ArrayOfObjectsalways an array with just a single (1) object like in your example? If not, does each object have some sort identifier to signal where a givennameandvalueneed to be added as property/value to? For example if becomes{ ArrayOfObjects: [{ a:1 }, { a:1, b:2 }] }, which object in the array wouldnameofcandvalueof3go to?ArrayOfObjectsto be an array if it's only going to ever have a single object?