Read more

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

Arne Hartherz
December 09, 2014Software engineer at makandra GmbH

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 }
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2014-12-09 11:22)