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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)