Javascript Merge数组更改为原始数组

时间:2017-10-05 10:33:11

标签: javascript angularjs arrays algorithm merge

我有一个像下面这样的数组;

[{
    name: 'a',
    color: 'red',
    children: 
    [{
        name: 'a1',
        color: 'red',
        children: 
        [{
            name: 'a11'
        }]
    },
    {
        name: 'a2'
        color: 'red',
    }]
},
{
    name: 'b'
    color: 'red',
}]

然后用户对前端进行更改,然后返回数组的新结构,如下所示;

[{
    name: 'a'
    color: 'red',
    children: 
    [{
        name: 'a1'
        color: 'red',
    },
    {
        name: 'a2'
        color: 'red',
        children: 
        [{
            name: 'a21',
            color: 'yellow'
        }]
    }]
},
{
    name: 'new'
    color: '',
},
{
    name: 'a11'
    color: 'red',
},
{
    name: 'b'
    color: 'red',
}]

正如您所看到的,有些对象已经移动,有些已被添加。然后我需要将更改合并回原始数组,而不是更改尚未更改的对象。

这个列表是由angular渲染的,所以如果我只用新的数组替换原始数组,它将再次渲染整个数组(这个数组可能很大)并且会导致速度变慢。

我尝试在lodash中使用合并功能但是我遇到了名为" new"的对象的问题。获得一种颜色"红色"由于名称为" b"在已经有颜色的原始数组中。

最有效的方法是什么?

1 个答案:

答案 0 :(得分:0)

Angular具有此angular.merge()的内置函数,适用于angular 1.6.5这种情况。请检查与角度版本的兼容性。

主要代码如下所示。

angular.merge($scope.source, $scope.changed);

此处$scope.source$scope.changed合并,更改已直接对$scope.source进行,无需LHS变量。

我试图在下面的小提琴中代表正在发生的事情。请检查此代码是否能够解决您的问题!

JSFiddle Demo