Sign in
SearchSEARCH
LANGUAGES
ADVANCED
Object.assign()
see all contributors
Object.assign()
Merging objects with same properties
Copying symbol-typed properties
Properties on the prototype chain and non-enumerable properties cannot be copied
Primitives will be wrapped to objects
Exceptions will interrupt the ongoing copying task
TheObject.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Syntax
Object.assign(target, ...sources)
Parameters
target
The target object.
sources
The source object(s).
Return value
The target object.
Description
Properties in the target?object will be overwritten by properties in the sources if they have the same key. ?Later sources'?properties will similarly overwrite earlier ones.
TheObject.assign()method only copiesenumerableandownproperties from a source object to a target object. It uses[[Get]]on the source and[[Set]]on the target, so it will invoke getters and setters. Therefore itassignsproperties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions, including their enumerability, into prototypesObject.getOwnPropertyDescriptor()andObject.defineProperty()should be used instead.
BothStringandSymbolproperties are copied.
In case of an error, for example if a property is non-writable, aTypeErrorwill be raised, and thetargetobject remains unchanged.
Note thatObject.assign()does not throw onnullorundefinedsource values.
Examples
Cloning an object
varobj={a:1};varcopy=Object.assign({},obj);console.log(copy);// { a: 1 }
Warning for Deep Clone
For deep cloning,?we?need to use other?alternatives. This is becauseObject.assign()copies the property reference when the property being assigned is an object.
functiontest(){leta={b:{c:4},d:{e:{f:1}}}letg=Object.assign({},a)leth=JSON.parse(JSON.stringify(a));console.log(g.d)// { e: { f: 1 } }g.d.e=32console.log('g.d.e set to 32.')// g.d.e set to 32.console.log(g)// { b: { c: 4 }, d: { e: 32 } }console.log(a)// { b: { c: 4 }, d: { e: 32 } }console.log(h)// { b: { c: 4 }, d: { e: { f: 1 } } }h.d.e=54console.log('h.d.e set to 54.')// h.d.e set to 54.console.log(g)// { b: { c: 4 }, d: { e: 32 } }console.log(a)// { b: { c: 4 }, d: { e: 32 } }console.log(h)// { b: { c: 4 }, d: { e: 54 } }}test();
Merging objects
varo1={a:1};varo2={b:2};varo3={c:3};varobj=Object.assign(o1,o2,o3);console.log(obj);// { a: 1, b: 2, c: 3 }console.log(o1);// { a: 1, b: 2, c: 3 }, target object itself is changed.
Merging objects with same properties
varo1={a:1,b:1,c:1};varo2={b:2,c:2};varo3={c:3};varobj=Object.assign({},o1,o2,o3);console.log(obj);// { a: 1, b: 2, c: 3 }
The properties are overwritten by other objects that have the same properties?later in the parameters order.
Copying symbol-typed properties
varo1={a:1};varo2={[Symbol('foo')]:2};varobj=Object.assign({},o1,o2);console.log(obj);// { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)Object.getOwnPropertySymbols(obj);// [Symbol(foo)]
Properties on the prototype chain and non-enumerable properties cannot be copied
varobj=Object.create({foo:1},{// foo is on obj's prototype chain.bar:{value:2// bar is a non-enumerable property.},baz:{value:3,enumerable:true// baz is an own enumerable property.}});varcopy=Object.assign({},obj);console.log(copy);// { baz: 3 }
Primitives will be wrapped to objects
varv1='abc';varv2=true;varv3=10;varv4=Symbol('foo');varobj=Object.assign({},v1,null,v2,undefined,v3,v4);// Primitives will be wrapped, null and undefined will be ignored.// Note, only string wrappers can have own enumerable properties.console.log(obj);// { "0": "a", "1": "b", "2": "c" }
Exceptions will interrupt the ongoing copying task
vartarget=Object.defineProperty({},'foo',{value:1,writable:false});// target.foo is a read-only propertyObject.assign(target,{bar:2},{foo2:3,foo:3,foo3:3},{baz:4});// TypeError: "foo" is read-only// The Exception is thrown when assigning target.fooconsole.log(target.bar);// 2, the first source was copied successfully.console.log(target.foo2);// 3, the first property of the second source was copied successfully.console.log(target.foo);// 1, exception is thrown here.console.log(target.foo3);// undefined, assign method has finished, foo3 will not be copied.console.log(target.baz);// undefined, the third source will not be copied either.
Copying accessors
varobj={foo:1,getbar(){return2;}};varcopy=Object.assign({},obj);console.log(copy);// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value.// This is an assign function that copies full descriptorsfunctioncompleteAssign(target,...sources){sources.forEach(source=>{letdescriptors=Object.keys(source).reduce((descriptors,key)=>{descriptors[key]=Object.getOwnPropertyDescriptor(source,key);returndescriptors;},{});// by default, Object.assign copies enumerable Symbols tooObject.getOwnPropertySymbols(source).forEach(sym=>{letdescriptor=Object.getOwnPropertyDescriptor(source,sym);if(descriptor.enumerable){descriptors[sym]=descriptor;}});Object.defineProperties(target,descriptors);});returntarget;}varcopy=completeAssign({},obj);console.log(copy);// { foo:1, get bar() { return 2 } }
Polyfill
Thispolyfilldoesn't support symbol properties, since ES5 doesn't have symbols anyway:
if(typeofObject.assign!='function'){(function(){Object.assign=function(target){'use strict';// We must check against these specific cases.if(target===undefined||target===null){thrownewTypeError('Cannot convert undefined or null to object');}varoutput=Object(target);for(varindex=1;index
Specifications
SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Object.assign' in that specification.StandardInitial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Object.assign' in that specification.Draft
Browser compatibility
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support4534(34)No?support(Yes)329
See also
Enumerability and ownership of properties
Document Tags and Contributors
Tags:
Contributors to this page:sjohnsonaz,RocAlayo,Asuza,Ende93,HarrisonB,SphinxKnight,Normanlife,allan-bonadio,eduardoboucas,chharvey,popigg,bergus,fscholz,taiyaki32p,irnc,ajmichaels,jacksonrayhamilton,iamchenxin,Willson,WebReflection,jiraiya,rwaldron,pixelkritzel,SamuelMarks,marxus,makowski,yan,vaibhavsinghal87,andrewashbacher,nicolo-ribaudo,roczinskisquared,Mingun,olegskl,ziyunfei,kdex,The_8472,davezatch,Waldo,evilpie,megawac,dbruant
Last updated by:sjohnsonaz,Sep 14, 2016, 10:35:52 AM
SEE ALSO
Object.prototype.__noSuchMethod__
Object.assign()
Object.getOwnPropertyDescriptor()
Object.getOwnPropertyDescriptors()
Object.getOwnPropertySymbols()
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Inheritance:
? 2005-2016 Mozilla Developer Network and individual contributors.
Content is available underthese licenses.
Other languages:English (US) (en-US)Català (ca)Deutsch (de)Espa?ol (es)Fran?ais (fr)Italiano (it)日本語 (ja)Português (do?Brasil) (pt-BR)Русский (ru)中文 (簡體) (zh-CN)