9

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.

Maxime Girou
  • 1,511
  • 2
  • 16
  • 32
Andy Thomas
  • 1,219
  • 3
  • 19
  • 33
  • @MaheerAli I don't want to modify foo. I want to create a new object using foo values. – Andy Thomas May 28 '19 at 14:05
  • Possible duplicate of [Using spread operator to update an object value](https://stackoverflow.com/questions/49491393/using-spread-operator-to-update-an-object-value) and [modifying an object using … in JavaScript](https://stackoverflow.com/questions/55680620) and [Update Multiple Properties of an object with spread operator](https://stackoverflow.com/questions/41878169) – adiga May 28 '19 at 14:09

3 Answers3

13

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
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)
Kobe
  • 6,226
  • 1
  • 14
  • 35
-2

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);
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32