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' } }
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With