Posted about 1 month ago. Visible to the public.

Merging two JavaScript objects

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

Copy
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:

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

When you have Unpoly

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

When you only have ES5

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

Note for Lodash users

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

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more