Reputation: 11
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
Upvotes: 1
Views: 3862
Reputation: 9168
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)
Upvotes: 1