Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS clone objects using spread operator and change one field [duplicate]

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.

like image 421
Andy Thomas Avatar asked May 28 '19 14:05

Andy Thomas


People also ask

Does Spread operator clone an object?

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.

Does spread operator create a new copy?

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.


2 Answers

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)
like image 176
Maheer Ali Avatar answered Nov 04 '22 00:11

Maheer Ali


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)
like image 44
Kobe Avatar answered Nov 04 '22 00:11

Kobe