1

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

3
  • You need to use the correct name of the first key it's firstKey not newFirstKey. Try const newData = {...data, firstKey: newFirstValue} Commented May 6, 2022 at 11:23
  • Because that's what the code does - it adds a new key/value pair to the object. Maybe just delete the old property? Commented May 6, 2022 at 11:24
  • Can you explain what your expected result is instead? Commented May 6, 2022 at 11:37

1 Answer 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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.