angularjs - 扩展递归 [英] angularjs - extend recursive
问题描述
我想扩展一些递归属性(又名深度复制).很像jQuery.我不只包括 jquery 的 b/c 一件事.
I would like to extend some properties recursive (aka. deep copy). much like jQuery does. I'm not including jquery only b/c of one thing.
jQuery.extend( true, target, object1 )
你知道有什么优雅的方法可以用简单的 javascript 或 angularjs 来实现吗?
is there any elegant way you know of that does it with simple javascript or angularjs?
更新请看一看并尝试完成相同的结果http://plnkr.co/edit/GHabYbyhsqtfBPtplksO?p=preview
update please take a look and try to accomplish the same result http://plnkr.co/edit/GHabYbyhsqtfBPtplksO?p=preview
我确实研究了 .copy() 但属性(对象)被删除了"
i did look into .copy() but the "properties (for objects) are deleted"
推荐答案
这是一个基于 angular.extend 函数的 extendDeep 函数.如果你把它添加到你的 $scope 中,你就可以调用
Here is an extendDeep function based off of the angular.extend function. If you add this to your $scope, you would then be able to call
$scope.meta = $scope.extendDeep(ajaxResponse1.myMeta, ajaxResponse2.defaultMeta);
并获得您正在寻找的答案.
and get the answer you are looking for.
$scope.extendDeep = function extendDeep(dst) {
angular.forEach(arguments, function(obj) {
if (obj !== dst) {
angular.forEach(obj, function(value, key) {
if (dst[key] && dst[key].constructor && dst[key].constructor === Object) {
extendDeep(dst[key], value);
} else {
dst[key] = value;
}
});
}
});
return dst;
};
注意:此函数具有将值从后面的参数复制到前面的参数的副作用.要对此副作用进行简单的修复,您可以将 dst[key] = value
更改为 dst[key] = angular.copy(value)
.
Note: This function has the side-effect of copying values from later arguments into the earlier arguments. For a simple fix to this side effect, you can change dst[key] = value
to dst[key] = angular.copy(value)
.
这篇关于angularjs - 扩展递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!