12

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.

2

3 Answers 3

17

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)

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

Comments

8

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)

Comments

-1

Use the spread operator and put your property you wanna change after it

let foo = {a : "Other A", b : "OtherB", c : "OtherC"} let obj = {a: 'A', b: 'B', c: 'C'} obj = {...foo, c : 'D'}; console.log(obj);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.