简体   繁体   English

在 Angular Javascript 中合并组合匹配对象的数组

[英]Merge Arrays Combining Matching Objects in Angular Javascript

I have 2 array objects in Angular JS that I wish to merge (overlap/combine) the matching ones.我在 Angular JS 中有 2 个数组对象,我希望合并(重叠/组合)匹配的对象。

For example, the Array 1 is like this:例如,数组 1 是这样的:

[
    {"id":1,"name":"Adam"},
    {"id":2,"name":"Smith"},
    {"id":3,"name":"Eve"},
    {"id":4,"name":"Gary"},
]

Array 2 is like this:数组2是这样的:

[
    {"id":1,"name":"Adam", "checked":true},
    {"id":3,"name":"Eve", "checked":true},
]

I want the resulting array after merging to become this:我希望合并后的结果数组变成这样:

[
    {"id":1,"name":"Adam", "checked":true},
    {"id":2,"name":"Smith"},
    {"id":3,"name":"Eve", "checked":true},
    {"id":4,"name":"Gary"},
]

Is that possible?那可能吗? I have tried angular's array_merge and array_extend like this:我试过 angular 的array_mergearray_extend这样的:

angular.merge([], $scope.array1, $scope.array2);
angular.extend([], $scope.array1, $scope.array2);

But the above method overlap the first 2 objects in array and doesn't merge them based on matching data.但是上述方法重叠了数组中的前 2 个对象,并且不会根据匹配数据合并它们。 Is having a foreach loop the only solution for this?有一个foreach循环是唯一的解决方案吗?

Can someone guide me here please?有人可以在这里指导我吗?

Not sure if this find of merge is supported by AngularJS.不确定 AngularJS 是否支持这种合并发现。 I've made a snippet which does exactly the same:我制作了一个完全相同的片段:

 function merge(array1, array2) { var ids = []; var merge_obj = []; array1.map(function(ele) { if (!(ids.indexOf(ele.id) > -1)) { ids.push(ele.id); merge_obj.push(ele); } }); array2.map(function(ele) { var index = ids.indexOf(ele.id); if (!( index > -1)) { ids.push(ele.id); merge_obj.push(ele); }else{ merge_obj[index] = ele; } }); console.log(merge_obj); } var array1 = [{ "id": 1, "name": "Adam" }, { "id": 2, "name": "Smith" }, { "id": 3, "name": "Eve" }, { "id": 4, "name": "Gary" }, ] var array2 = [{ "id": 1, "name": "Adam", "checked": true }, { "id": 3, "name": "Eve", "checked": true }, ]; merge(array1, array2);

Genuinely, extend in Angular works with object instead of array.真正地,在 Angular 中extend使用对象而不是数组。 But we can do small trick in your case.但是我们可以在你的情况下做一些小技巧。 Here is another solution.这是另一种解决方案。

// a1, a2 is your arrays
// This is to convert array to object with key is id and value is the array item itself
var a1_ = a1.reduce(function(obj, value) {
    obj[value.id] = value;
    return obj;
}, {});
var a2_ = a2.reduce(function(obj, value) {
    obj[value.id] = value;
    return obj;
}, {});
// Then use extend with those two converted objects
var result = angular.extend([], a1_, a2_).splice(1)

Notes:笔记:

  • For compatibility, reduce may not work.为了兼容性, reduce可能不起作用。
  • The after array will replace the previous one. after 数组将替换前一个数组。 This is because of implementation of extend in Angular.这是因为在 Angular 中实现了extend

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM