Read more

Merging two JavaScript objects

Henning Koch
July 08, 2020Software engineer at makandra GmbH

Let's say you want to merge the properties of two JavaScript objects:

let a = { foo: 1, bar: 2 }
let b = { bar: 3, baz: 4 }

let merged = merge(a, b) // => { foo: 1, bar: 3, baz: 4 }
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Depending on your build, there are several ways to implement merge().

When you have ES6

When you have an ES6 transpiler or don't support IE11, you may use the spread operator (...) to expand both objects into a new object literal:

let merged = { ...a, ...b }

When you have Unpoly Show archive.org snapshot

let merged = up.util.merge(a, b)

When you only have ES5

let merged = Object.assign({}, a, b)

Note for Lodash users

Lodash has _.merge() Show archive.org snapshot , but that merges arrays and objects recursively. Make sure this is what you want.

Posted by Henning Koch to makandra dev (2020-07-08 14:33)