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

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)