I am trying to create a new array of objects with a nested for loop. I am calling the Object.assign
method with a spread argument to create a new object, but I think the problem lies with there being the same object key for each item and I only get an output with the last item in the loop. Here is the code:
let array1 = ["first", "second", "third", "fourth"];
let array2 = [
[1, "a", "b", "c"],
[2, "d", "e", "f"],
[3, "g", "h", "i"],
[4, "j", "k", "l"],
[5, "m", "n", "o"]
];
let matchedVals = [];
let finalVals = [];
for (let j = 0; j < array1.length; j++) {
for (let i = 0; i < array2.length; i++) {
matchedVals.push({ [array2[i]]: array1[j][i] })
finalVals.push(Object.assign(...matchedVals))
}
}
//End Result Expected
// [
// {
// "first": 1,
// "second": "a",
// "third": "b",
// "forth": "c"
// }, {
// "first": 2,
// "second": "d",
// "third": "e",
// "forth": "f"
// }, {
// "first": 3,
// "second": "g",
// "third": "e",
// "forth": "h"
// }
// ...
// ]
I am sure there is something simple, but I am not familiar enough with Object.Assign to understand what I can do to get around this issue.