How to copy an object by values?

const obj1 = {a: 1, b: 2}
const obj2 = {c: 3, a: 4}

// option #1: Object.assign
const obj3 = Object.assign(obj1, obj2)

// option #2: spread operator
const obj4 = {...obj1, ...obj2}

// output: { a: 4, b: 2, c: 3 }
console.log(obj3)

// output: { a: 4, b: 2, c: 3 }
console.log(obj4)
Copy

December 1st, 2019

# Clone an object

Add to bookmarks

Both the Spread Operator (...) and Object.assign(target, ...sources) can be used to copy an object by it's values and creates a new object without reference to the source object.

HomeBookmarks