Say I have an object: {a: 'A', b: 'B', c: 'C'}
and I want to create a new object from it that would have the same values except I want to set c: 'D'
.
What is the syntax for that? I tried something like:
{c: 'D', ...rest} = {...foo}
But it is not a valid syntax.
Using Spread Using spread will clone your object. Note this will be a shallow copy. As of this post, the spread operator for cloning objects is in Stage 4.
When we're talking about composite data types, the spread operator allows us to make copies of the original data (whether it be an array or object) and create a new copy of it in memory.
You spread syntax on right hand side.
Note: Use Spread Operator first then set the new property. For example {c:'D',...foo}
will not work.
let foo = {a: 'A', b: 'B', c: 'C'};
let res = {...foo, c:'D'};
console.log(res)
You would write your code like this:
var obj1 = {a: 'A', b: 'B', c: 'C'}
var obj2 = {...obj1, c: 'D'}
console.log(obj2)
Writing ...obj1
will fill obj2
with obj1
's contents, and writing c: 'D'
will overwrite c: 'c'
.
Note, ordering is important, as maheer mentioned, because the object will be written in order, from each property, which can mess up ordering of keys, and setting incorrect values:
var obj = {a: 'A', b: 'B', c: 'C'}
var ex1 = {...obj, c: 'D'}
var ex2 = {c: 'D', ...obj}
var ex3 = {c: 'D', ...obj, c: 'E'}
console.log('Example 1:', ex1)
console.log('Example 2:', ex2)
console.log('Example 3:', ex3)
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