只是想知道将这两个数组合并在一起的最佳方法是什么。
示例
var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]
希望将它们合并到:
var c = ["ID":11021, ASSET_NAME:"panda", service_name: ['open requests','open tickets']]
任何帮助都会很棒。
由于
答案 0 :(得分:1)
您可以使用一个对象来存储ID和reduce()
来创建新的合并对象数组。
var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]
var obj = {}
var result = a.concat(b).reduce(function(r, e) {
if (!obj[e.ID]) {
obj[e.ID] = {
ID: e.ID,
ASSET_NAME: e.ASSET_NAME,
service_name: []
}
r.push(obj[e.ID])
}
obj[e.ID].service_name.push(e.SERVICE_NAME)
return r
}, [])
console.log(JSON.stringify(result, 0, 4))

答案 1 :(得分:0)
您可以使用数组的 map 方法,如下所示:
var a = [{'eprid':112}, {'asset_name':'panda'}, {'service_name': 'open tickets'}];
var b = [{'eprid':112}, {'asset_name':'panda'}, {'service_name': 'open requests'}];
var c = a.map((obj, i) => {
for (key in obj) {
if(obj[key] !== b[i][key]) {
obj[key] = [obj[key], b[i][key]]
}
return obj;
}
})
console.log(c) // [{'eprid':112}, {'asset_name':'panda'}, {'service_name': ['open ticket', 'open requests']}]