angularjs - 递归扩展 [英] angularjs - extend recursive

查看:132
本文介绍了angularjs - 递归扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想递归扩展一些特性(亦称深层副本)。
就像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?

更新
请看看,并尝试完成相同的结果
<一href=\"http://plnkr.co/edit/GHabYbyhsqtfBPtplksO?p=$p$pview\">http://plnkr.co/edit/GHabYbyhsqtfBPtplksO?p=$p$pview

我没有考虑.copy(),但属性(对象)都将被删除

i did look into .copy() but the "properties (for objects) are deleted"

推荐答案

下面是基于该angular.extend功能的extendDeep功能。如果您添加到您的$的范围,那么您需要能够调用

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 [关键] =值 DST [关键] = angular.copy(值)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆