类似于excel中的vlookup。我在 javascript 中有 2 个对象数组。我想在数组 #2 中查找数组 #1 中的一个对象,并将一个对象从数组 #2 推送到数组 #1。我希望数组 #1 中的每个值都发生这种情况。这样我就可以在一个地方拥有一个包含所有我想要的信息的数组。
例如,
let array1 = [
{"first":"Ana","last":"Anderson","id":"0001"},
{"first":"Bob","last":"Brown","id":"0002"},
{"first":"Charlie","last":"Clark","id":"0003"},
{"first":"Danielle","last":"Dunn","id":"0004"}
]
let array2 = [
{"age":"38","id":"0002","eyeColor":"hazel","hieght":"5.5"},
{"age":"45","id":"0001","eyeColor":"brown","hieght":"5"},
{"age":"23","id":"0003","eyeColor":"blue","hieght":"6"}
]
如何制作一个显示以下内容的数组? 我一直在尝试使用indexof和push的for循环
let array3 = [
{"first":"Ana","last":"Anderson","id":"0001","age":"45","eyeColor":"brown","hieght":"5"},
{"first":"Bob","last":"Brown","id":"0002","age":"38","eyeColor":"hazel","hieght":"5.5"},
{"first":"Charlie","last":"Clark","id":"0003","age":"23","eyeColor":"blue","hieght":"6"},
{"first":"Danielle","last":"Dunn","id":"0004","age":"","eyeColor":"","hieght":""}
]
使用循环迭代array1,对于array1中的每个对象,在array2中搜索匹配的id并合并信息。
let array1 = [
{"first":"Ana","last":"Anderson","id":"0001"},
{"first":"Bob","last":"Brown","id":"0002"},
{"first":"Charlie","last":"Clark","id":"0003"},
{"first":"Danielle","last":"Dunn","id":"0004"}
];
let array2 = [
{"age":"38","id":"0002","eyeColor":"hazel","hieght":"5.5"},
{"age":"45","id":"0001","eyeColor":"brown","hieght":"5"},
{"age":"23","id":"0003","eyeColor":"blue","hieght":"6"}
];
let array3 = [];
for (let i = 0; i < array1.length; i++) {
let matchedObject = array2.find(obj => obj.id === array1[i].id) || {};
let mergedObject = { ...array1[i], ...matchedObject };
array3.push(mergedObject);
}
console.log(array3);