Reputation: 3
I have two arrays like this
const arr1 = ["name", "age", "spouseName", "kids"];
const arr2 = [["John", "Jack"], [31, 44], ["Jill", "Emily"], [3, 2]];
I need to map the elements of arr1 to each nested element at the same index of arr2 so that I get result in an array with two objects like this
result = [ { "name" : "John", "age" : 31, "spouseName": "Jill", "kids" : 3 },
{ "name" : "Jack", "age" : 44, "spouseName": "Emily", "kids" : 2 }]
I have tried using nested forEach to loop over each of element in arr2 but it only spits out the items in index 1 and not at index 0 as it get overwritten in the loop
arr2.forEach((element, index) => {
element.forEach((el) => {
result[arr1[index]] = el
})
});
I know I am missing something but can't figure out
Upvotes: 0
Views: 55
Reputation: 58462
You can loop through the names in array 2 and assuming the following arrays have the correct number of elements in you can use the index of that name to get the corresponding items from the other arrays:
const arr1 = [];
const arr2 = [["John", "Jack"], [31, 44], ["Jill", "Emily"], [3, 2]];
arr2[0].forEach((item, index) => {
arr1.push({
"name": item,
"age": arr2[1][index],
"spouseName": arr2[2][index],
"kids": arr2[3][index],
});
})
console.log(arr1);
If you need to use arr1
as your property names and you don't know the number of items in arr1
, I would do it like this:
const arr1 = ["name", "age", "spouseName", "kids"];
const arr2 = [
["John", "Jack", "1", "2", "3"],
[31, 44, 22, 41, 42],
["Jill", "Emily", "1", "2", "3"],
[3, 2, 1, 5, 2]
];
const result = arr2[0].map((name, index) => {
let returnValue = {};
returnValue[arr1[0]] = name;
for (let i = 1; i < arr1.length; i++) {
returnValue[arr1[i]] = arr2[i][index];
}
return returnValue;
});
console.log(result)
It is a slightly more efficient way than using reduce in your map loop: https://jsbench.me/zpl6lvmb6r/1
Upvotes: 0
Reputation: 492
You can loop through the arrays as follows:
const arr1 = ["name", "age", "spouseName", "kids"];
const arr2 = [["John", "Jack"], [31, 44], ["Jill", "Emily"], [3, 2]];
result = arr2[0].map((_, i) => arr1.reduce((acc, k, j) => {
acc[k] = arr2[j][i];
return acc;
}, {}));
console.log(result);
Upvotes: 1