angularjs - 扩展递归

End*_*ess 22 angularjs

我想扩展一些属性递归(aka.深拷贝).很像jQuery.我不包括jquery只有b/c的一件事.

jQuery.extend( true, target, object1 )
Run Code Online (Sandbox Code Playgroud)

有没有你知道的优雅方式,用简单的javascript或angularjs吗?

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

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

Rya*_*ill 28

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

$scope.meta = $scope.extendDeep(ajaxResponse1.myMeta, ajaxResponse2.defaultMeta);
Run Code Online (Sandbox Code Playgroud)

并得到你正在寻找的答案.

$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;
};
Run Code Online (Sandbox Code Playgroud)

注意:此函数具有将后续参数中的值复制到先前参数的副作用.有关此副作用的简单修复,您可以更改dst[key] = valuedst[key] = angular.copy(value).


Jul*_*n P 16

这里的所有答案都适用于1.4之前Angular版本

从Angular 1.4开始,您可以使用以下内容angular.merge:

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

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


Ste*_*wie 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;
}
Run Code Online (Sandbox Code Playgroud)

Plunker

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