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

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)