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 Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)