Clone or merge objects using Object.assign() in JavaScript
Object.assign( ) method help us to copy the values of all enumerable properties from the one or more source objects to the target object.It returns the target object.
Syntax:
Object.assign(target, source);
Merging two objects
In this example, we are merging user
and posts
object into a single object using Object.assign()
method.
const user = {
id:1,
name:"gowtham"
}
const posts = {
title:"my post",
body:"demo"
}
console.log(Object.assign(user, posts));
// {body: "demo", id: 1, name: "gowtham", title: "my post"}
Merge and overwrite the same properties
We can also merge and overwrite the same property names using Object.assign()
.
const user1 = {
id:1,
name:"gowtham"
}
const user2 = {
id:2,
name:"sai"
}
const user3 = {
id:3,
name:"tony"
}
console.log(Object.assign(user1, user2, user3));
// {id: 3, name: "tony"}
Cloning Objects
const user = {
id:16,
name:"gowtham"
}
const cloneuser = Object.assign({}, user);
console.log(cloneuser); // {id: 16, name: "gowtham"}