Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 911
JDillon522 Avatar asked Nov 13 '13 22:11

JDillon522


1 Answers

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

like image 187
Shital Shah Avatar answered Oct 06 '22 05:10

Shital Shah