JavaScript merge objects | Example code

  • by

Use spread operator ( ...) to merge objects in JavaScript. If objects have a property with the same name, then the right-most object property overwrites the previous one.

let merged = {...obj1, ...obj2};

JavaScript merge objects

Simple example code creates a new object that combines the properties of all the objects. The following example uses the spread operator (...) to merge the person and job objects into the employee object:

<!DOCTYPE html>
<html>
<body>

  <script>
   let person = {
    fname: 'John',
    lanme: 'Doe',
    age: 25,
    Salary: '100$'
  };


  let job = {
    title: 'SE',
    location: 'USA'
  };

  let employee = {
    ...person,
    ...job
  };

  console.log(employee);

</script>

</body>
</html> 

Output:

JavaScript merge objects

Another method

Merge objects using Object.assign() method. This method allows you to copy all enumerable own properties from one or more source objects to a target object, and return the target object:

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356'
};


let job = {
    jobTitle: 'JavaScript Developer',
    country: 'USA'
};


let employee = Object.assign(person, job);
console.log(employee);

Output:

{
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356',
    jobTitle: 'JavaScript Developer',
    country: 'USA'
}

Do comment if you have any doubts or suggestions on this JS Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.