'how to replace a single key value pair from an object in react.js
I have a single object of with key value pair, and i need to replace the first key value pair with a new key value in react.js. I have tried to make immutable process like
const data = {
firstKey : firstValue,
secondKey : secondValue,
thirdKey : thirdValue
}
const newData = {...data, newFirstKey: newFirstValue}
but its adding a new key value pair to the object
Solution 1:[1]
That is expected behavior. See MDN docs on spreading Objects.
If you want to replace a value you have to use the property name which you want to replace and set the new value.
const data = {
firstKey : "firstValue",
secondKey : "secondValue",
thirdKey : "thirdValue"
}
const newData = {...data, firstKey: "newFirstValue"}
console.log(newData)
If you use a new unknown property name, this new property will be added to the object.
const data = {
firstKey : "firstValue",
secondKey : "secondValue",
thirdKey : "thirdValue"
}
const newData = {...data, unknownProperty: "newFirstValue"}
console.log(newData)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mushroomator |