Underscore / LoDash: How to extend (or merge) into a new object

Updated . Posted . Visible to the public.

When using _.extend/_.assign or _.merge, you will modify the destination object.

object1 = { foo: 23, bar: 42 }
object2 = { bar: 99 }

_.extend(object1, object2) // => { foo: 23, bar: 99 }
object1 // => { foo: 23, bar: 99 }

If you do not want to do that, simply extend into a new object:

object1 = { foo: 23, bar: 42 }
object2 = { bar: 99 }

_.extend({}, object1, object2) // => { foo: 23, bar: 99 }
object1 // => { foo: 23, bar: 42 }

Note how our _.extend statement receives {} as its first argument.

Arne Hartherz
Last edit
Arne Hartherz
Keywords
clone
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-12-09 10:22)