Merge Objects in JavaScript Code Example

Last Updated On Thursday 20th Jan 2022

Object.Assign Method

  • Object.assign() method is used to merge objects.
  • You Can Merge objects without any limits

Example 1:

	const bookName = {
    name: 'Billy Summers'
}

const bookAuthor = {
    author: 'Stephen King'
}

const book = Object.assign(bookAuthor, bookName)

console.log(book);
// {
//   author: 'Stephen King',
//   name: 'Billy Summers'
// }

	

Spread Operator

  • Spread operator is an excellent way to merge two objects in JavaScript.

Example 2:

	const bookName = {
    name: 'The Wisdom of Crowds: Book Three.'
}

const bookAuthor = {
    author: 'Joe Abercrombie'
}

const book = {
    ...bookName,
    ...bookAuthor
}

console.log(book);
// {
//  name: 'The Wisdom of Crowds: Book Three',
//  author: 'Joe Abercrombie'
// }