Merging two JavaScript objects

Posted . Visible to the public.

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 }

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.

Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2020-07-08 12:33)