How to Merge Objects in JavaScript
An object is frequently used to store data. Sometimes you end up with multiple data objects that you need to combine their contents. In this article, I will show you several ways to merge objects in JavaScript.
Format of an Object
An Object is a collection of key-value pairs. Let’s take a look at this simple object:
const customer = { name: 'Jennifer', age: 60 }
Merging Objects using Object.assign()
The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Here is the syntax:
Object.assign(target, ...sources)
Using Object.assign
does not create a new object. Instead, it copies all the source objects into the target object. Let's look at an example.
const target = { name: 'Jennifer', age: 60 }; const source = { city: 'Athens', state: 'GA' }; Object.assign(target, source); console.log(target); // { name: 'Jennifer', age: 60, city: 'Athens', state: 'GA' }