I'm working on a React Native project. Right now, I'm adding new key/value inside an object.
It's working but I would like to know if there is a better way to do it or if you have any advice.
I'm still new to ReactJS/React Native and not 100% skills on Javascript. So here's my code :
My object
state = {
result : {
"q1":1
}
}
My function to add key/value and modify the state of result
:
_getValue = (id, value) => {
var newObj = this.state.result;
newObj[id] = parseInt(value);
this.setState({
result: newObj
}, () => {
console.log(this.state.result)
})
}
Thank you !
To add a key/value pair to all objects in an array:Use the Array. map() method to iterate over the array. On each iteration, use the spread syntax to add the key/value pair to the current object. The key/value pair will get added to all objects in the new array.
Objects cannot be used as keys. React js requires a key to be a string or a number and should be unique.
You create your object (including its id property) and then you add it to the result array. You add the id property to the last object in your result array (since you talk about "newly created data" I am assuming it is always the last item).
this should work fine.
this.setState({
result: {
...this.state.result,
[id]: value
}
});
it uses modern/new features such as object spread (...this.state.result
) and dynamic object properties ([id]: value
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With