[英]Merge objects based on same key from different positions in an array
我有20个对象的2个数组,我想按名称合并。 每个数组中名称的顺序是不同的,顺序很重要,必须照原样保留。 这使我无法采用传统的排序和for
循环方法。 基本上,我有:
var tempList1 = [
{'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1},
{'manager':'Tom', 'x1':0, 'y1':50, 'x2':1, 'y2':1},
{'manager':'Julie', 'x1':0, 'y1':80, 'x2':1, 'y2':1},
...
];
var tempList2 = [
{'manager':'Tom', 'x3':0, 'y3':10, 'x4':1, 'y4':1},
{'manager':'Julie', 'x3':0, 'y3':90, 'x4':1, 'y4':1},
{'manager':'John', 'x3':0, 'y3':50, 'x4':1, 'y4':1},
...
];
请注意, John
是在索引0
中tempList1
但在指数2
的tempList2
。 当我尝试:
for (var k = 0; k < managerList.length; k++) {
let merged = {...tempList1[k],...tempList2[k]}
combinedList.push(merged);
}
我犯了一个错误,即假设每个数组中的顺序相同-当顺序不同时。
最终结果应为:
var combinedList = [
{'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1, 'x3':0, 'y3':50, 'x4':1, 'y4':1},
{'manager':'Tom', 'x1':0, 'y1':50, 'x2':1, 'y2':1, 'x3':0, 'y3':10, 'x4':1, 'y4':1},
{'manager':'Julie', 'x1':0, 'y1':80, 'x2':1, 'y2':1, 'x3':0, 'y3':90, 'x4':1, 'y4':1}
];
如何合并对象,以便只有同一manager
值的对象才能在数组中相互合并?
从其中一个列表中,创建一个由manager
索引的对象。 然后,当遍历其他列表时,只需查找相同的manager
属性并合并:
var tempList1 = [ {'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1}, {'manager':'Tom', 'x1':0, 'y1':50, 'x2':1, 'y2':1}, {'manager':'Julie', 'x1':0, 'y1':80, 'x2':1, 'y2':1} ]; var tempList2 = [ {'manager':'Tom', 'x3':0, 'y3':10, 'x4':1, 'y4':1}, {'manager':'Julie', 'x3':0, 'y3':90, 'x4':1, 'y4':1}, {'manager':'John', 'x3':0, 'y3':50, 'x4':1, 'y4':1} ]; const list1ByManager = tempList1.reduce((a, item) => { a[item.manager] = item; return a; }, {}); const combined = tempList2.map((item2) => ({ ...list1ByManager[item2.manager], ...item2 })); console.log(combined);
由于每个管理需要一个案例,我将您的数组转换为以经理名称为键的对象,然后再次转换为对象数组
var tempList1 = [ {'manager':'John', 'x1':0, 'y1':0, 'x2':1, 'y2':1}, {'manager':'Tom', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, {'manager':'Julie', 'x1':0, 'y1':0, 'x2':1, 'y2':1}, ].reduce(function(result, obj) { result[obj.manager] = obj return result }, {}); console.log(tempList1) var tempList2 = [ {'manager':'Tom', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, {'manager':'Julie', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, {'manager':'John', 'x3':0, 'y3':0, 'x4':1, 'y4':1}, ].reduce(function(result, obj) { result[obj.manager] = obj return result }, {}); var temp = [] for (var key in tempList1) { temp.push({ ...tempList1[key], ...tempList2[key] }) } console.log(temp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.