Similar to a vlookup in excel. I have 2 object arrays in javascript. I want to look up an object from array #1 in array #2 and push an object from array #2 to the array #1. I want this to happen for each value in array #1. This way I can have a single array with all of the information I want in one place.
for example,
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"}
]
How do I make an array that would display the following?
I have been trying a for loop with indexof and push
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":""}
]
2
Answers
use a loop to iterate through array1 and for each object in array1, searching for a matching id in array2 and merge the information.
Instead of working with the index , you can prefer to create a
Map
and store theid
as key. Then iterate the second object and check if theid
matches wit the key of the map. If it match then you can add those properties from the second array to the object of the first array.