合并具有不同键/属性的两个对象数组

时间:2018-10-23 08:51:44

标签: typescript

array1 = [{
        id: "David Moorman",
        current - margin: "500",
        current - customers: 123
    },
    {
        id: "Elaina Wasmus",
        current - margin: "600",
        current - customers: 45
    }
];
array2 = [{
    name: "Jose Maldonado",
    Purposed - margin: "700",
    purposed - customers: 100
}, {
    name: "David Moorman",
    Purposed - margin: "1000",
    purposed - customers: 34
}];

这是输出数组:

merge array = [{
    id: "David Moorman",
    current - margin: "500",
    Purposed - margin: "1000",
    current - customers: 123,
    purposed - customers: 100
}, {
    id: "Elaina Wasmus",
    current - margin: "600",
    Purposed - margin: NULL,
    current - customers: 45,
    purposed - customers: null
}, {
    id: "Jose Maldonado",
    current - margin: "0",
    Purposed - margin: "700",
    current - customers: null,
    purposed - customers: 100
}];

2 个答案:

答案 0 :(得分:2)

您可以为此使用lodash。
在这里,我将array2中的名称字段作为id字段。

 finalArr = _(_.flatten([array1, array2]))
                                        .groupBy('id')
                                        .map(_.spread(_.assign))
                                        .value();

仅当array2的id字段具有name字段的值时,此选项才有效。
两个数组都必须具有唯一的字段才能正确合并。

答案 1 :(得分:1)

据我了解,这将是我使用lodash的实现:

var finalArray = _.zipWith(array1, array2, function(a,b){
  return _.merge(a,b);
})

在此处查看lodash文档:https://lodash.com/docs/4.17.10