JDillon522 JDillon522 - 2 years ago 225
Javascript Question

Lodash - difference between .extend() / .assign() and .merge()

In the Lodash library, can someone provide a better explanation of merge and extend / assign.

Its a simple question but the answer evades me nonetheless.

Answer Source

Here's how extend/assign works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their properties. Entire object would be taken from source and set in to destination.

Here's how merge works: For each property in source, check if that property is object itself. If it is then go down recursively and try to map child object properties from source to destination. So essentially we merge object hierarchy from source to destination. While for extend/assign, it's simple one level copy of properties from source to destination.

Here's simple JSBin that would make this crystal clear: http://jsbin.com/uXaqIMa/2/edit?js,console

Here's more elaborate version that includes array in the example as well: http://jsbin.com/uXaqIMa/1/edit?js,console

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download