stackjlei
stackjlei

Reputation: 10035

fix js spread operator copying over deep values with same key

How can I fix below so the t:false persists to b?

https://jsfiddle.net/5gvxb7wL/

const a = { t: true, deep: { t: true} }
const b = { t: false, ...a }
console.log('a', a)
console.log('b', b)

consoles

"a", {
  deep: {
    t: true
  },
  t: true
}
"b", {
  deep: {
    t: true
  },
  t: true
}

Upvotes: 0

Views: 61

Answers (2)

AlekseyVY
AlekseyVY

Reputation: 26

When you use spread operator { t: false, ...a } like this, is you first change the value of the t, and then overwrite it with a copy of all values from object a so to use the spread operator correctly you need first spread a copy of an object that you copying, and then you change individual values that you need { ...a, t: false }.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370929

Spread a before listing the t: false; the later property listed/interpreted will take priority:

const a = { t: true, deep: { t: true} }
const b = { ...a, t: false }
console.log(b)

Upvotes: 4

Related Questions