angularjs - 扩展递归

时间:2013-03-09 12:57:44

标签: angularjs

我想扩展一些属性recursive(又名。深拷贝)。 很像jQuery。我不包括jquery只有b / c的一件事。

jQuery.extend( true, target, object1 )

你知道有什么优雅的方式可以用简单的javascript或angularjs吗?

更新 请看一下并尝试完成相同的结果 http://plnkr.co/edit/GHabYbyhsqtfBPtplksO?p=preview

我确实研究过.copy()但是“属性(对象)被删除了”

6 个答案:

答案 0 :(得分:28)

这是一个基于angular.extend函数的extendDeep函数。如果将其添加到$ scope,则可以调用

$scope.meta = $scope.extendDeep(ajaxResponse1.myMeta, ajaxResponse2.defaultMeta);

并获得您正在寻找的答案。

$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)

答案 1 :(得分:16)

此处的所有答案均适用于 Angular 1.4之前

的版本

从Angular 1.4开始,您可以使用angular.merge来做到这一点:

  

与extend()不同, merge()以递归方式下降到源对象的对象属性中,执行深层复制

https://docs.angularjs.org/api/ng/function/angular.merge

答案 2 :(得分:7)

function deepExtend(destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
}

Plunker

Src:https://gist.github.com/gregdangelo/2343158

答案 3 :(得分:1)

在Ryan的代码基础上,你可以缩短对象检查,你也不应该扩展功能,这样你就不会覆盖对象指针。

var extendDeep = function extendDeep(dst) {
    angular.forEach(arguments, function(obj) {
        if (obj !== dst) {
            angular.forEach(obj, function(value, key) {
                if (dst[key] && angular.isObject(dst[key])) {
                    extendDeep(dst[key], value);
                } else if(!angular.isFunction(dst[key])) {
                    dst[key] = value;
                }
            });
        }
    });
    return dst;
};

答案 4 :(得分:0)

与Ryan相同的解决方案,但支持数组合并

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 if (dst[key] && dst[key].constructor && dst[key].constructor === Array) {
                  dst[key].concat(value);
                } else if(!angular.isFunction(dst[key])) {
                  dst[key] = value;
                }
              }
            );
          }
        }
      );
      return dst;
    }

答案 5 :(得分:-1)

Angular有一个复制方法:

angular.copy

相关问题