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
CodePudding user response:
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);
CodePudding user response:
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);