Object.assign()
is a method in JavaScript that is used to copy or merge objects.
Object.assign()
performs a shallow copy; i.e., it only copies properties, not prototype methods.
Take a look at the function signature below:
Object.assign()
returns a target object.
let fruit = { name: 'Kiwi', price: 200 };// Cloning fruitlet cloned_fruit = Object.assign({}, fruit);console.log(cloned_fruit);// Adding a property to the clonelet kiwi = Object.assign({weight: 500}, fruit);console.log(kiwi);
### Merging objects
In case of a name collision between a source and target property, Object.assign()
will overwrite
the local property of the target object.
let fruit = { name: 'Kiwi', price: 200 };let details = {calories: 305, color: 'green'};// Merging objects to create a new objectlet kiwi = Object.assign({}, fruit, details);console.log(kiwi);// Observe that property calories exists in the source and target.let kiwi2= Object.assign({calories : 100}, fruit, details);console.log(kiwi2)
Free Resources