ES6 Object.assign() Sample

Available in Chrome 45+ | View on GitHub | Browse Samples


Object.assign() copies the values (of all enumerable own properties) from one or more source objects to a target object. It has a signature of Object.assign(target, ...sources). The target object is the first parameter and is also used as the return value. Object.assign() is useful for merging objects or cloning them shallowly.

Live Output

JavaScript Snippet

'use strict';

// Merge an object
let first = {name: 'Tony'};
let last = {lastName: 'Stark'};
let person = Object.assign(first, last);
// {name: 'Tony', lastName: 'Stark'}
// first = {name: 'Tony', lastName: 'Stark'} as the target also changed

// Merge multiple sources
let a = Object.assign({foo: 0}, {bar: 1}, {baz: 2});
// {foo: 0, bar: 1, baz: 2}

// Merge and overwrite equal keys
let b = Object.assign({foo: 0}, {foo: 1}, {foo: 2});
// {foo: 2}

// Clone an object
let obj = {person: 'Thor Odinson'};
let clone = Object.assign({}, obj);
// {person: 'Thor Odinson'}