by Sai gowtham

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"}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course