Skip to content

JavaScript merge objects | Example code

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

A 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'
}

Both Object.assign() and the object spread syntax create a new object and do not modify the original objects.

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

1 thought on “JavaScript merge objects | Example code”

  1. Object.assign copies all own enumerable properties from the source objects to the target one.

    The way you used it above, all properties of job object will be copied to the person object and then the extended person object will be assigned to the employee variable.

    Practically if you compare employee and person objects will be equal.

    In order to achieve what you intented to show, you will have to pass an empty object as the target object in the invocation of the method like bellow:

    let employee = Object.assign({}, person, job);

    In this case person remains unchanged and the employee contains the properties of both person and job objects.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading