Underscore.js中的递归/深度扩展/分配? [英] Recursive/deep extend/assign in Underscore.js?
问题描述
有没有办法让Underscore.js extend
功能:
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.
...递归工作?
实际上,在$ code> creditOperation 中的查询
属性将会完全覆盖 baseOperation
中定义的查询
属性:
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));
我想获得此 creditOperation
:
{
host: 'gateway.skebby.it',
pathname: 'api/send/smseasy/advanced/http.php',
protocol: 'https',
query: {
'username': 'foo',
'password': 'bar',
'method': 'baz'
}
}
推荐答案
不,下划线不包含深度扩展因为处理不同类型的对象太复杂了。相反,鼓励用户实现他们自己的解决方案并支持他们需要的东西。
No, Underscore will not contain a deep extend since it's too complicated to deal with different types of objects. Instead, users are encouraged to implement their own solutions with the support for what they need.
在你的情况下,它只是普通的对象,所以实现非常简单:
In your case it's only plain objects, so an implementation is quite straightforward:
_.deepObjectExtend = function(target, source) {
for (var prop in source)
if (prop in target)
_.deepObjectExtend(target[prop], source[prop]);
else
target[prop] = source[prop];
return target;
}
这篇关于Underscore.js中的递归/深度扩展/分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!