Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive/deep extend/assign in Underscore.js?

Is there any way to get Underscore.js extend function:

Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.

... to work recursively?

Actually, query property in creditOperation is going to completely override the query property defined in baseOperation:

var url = require('url')   , _ = require('underscore'),   , baseOperation = {         host: 'gateway.skebby.it',         pathname: 'api/send/smseasy/advanced/http.php',         protocol: 'https',         query: {             'username': 'foo',             'password': 'bar',         }     };  var creditOperation = _.extend(baseOperation, {     query: {         'method': 'baz'     } });  console.log(url.format(creditOperation)); 

I'd like to obtain this creditOperation:

{     host: 'gateway.skebby.it',     pathname: 'api/send/smseasy/advanced/http.php',     protocol: 'https',     query: {         'username': 'foo',         'password': 'bar',         'method': 'baz'     } } 
like image 929
gremo Avatar asked Feb 12 '13 23:02

gremo


People also ask

Can you use underscore in JavaScript?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications.

How does _ Extend Work?

The _. extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated.

Why is JavaScript underscore better?

It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore. js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.


1 Answers

With Lodash (fork of underscore) you can. Lodash's _.extend method accept third (or higher) parameter to be a function, that receives values (old and new); So you can do something like this:

var deep = function(a, b) {     return _.isObject(a) && _.isObject(b) ? _.extend(a, b, deep) : b; };  var a = {a:{b:{c:1}}},     b = {a:{b:{z:1}}};  _.extend(a,b,deep); 

upd. As Paolo Moretti said in comments, there is the same function in lodash called _.merge:

_.merge(a,b); 
like image 51
Sergey Kamardin Avatar answered Sep 28 '22 01:09

Sergey Kamardin