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 online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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)