I want to map the key of one array to another nested array. Both arrays have the same length.
Before:
const idListToInsert = [{ idToInsert: 1 }, { idToInsert: 3 }, { idToInsert: 4 }];
const otherObjectList = [
[{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
[{ id: 5 }, { id: 6 }, { id: 7 }],
[{ id: 8 }, { id: 9 }],
];
Target:
const targetList = [
[
{ id: 1, idToInsert: 1 },
{ id: 2, idToInsert: 1 },
{ id: 3, idToInsert: 1 },
{ id: 4, idToInsert: 1 },
],
[
{ id: 5, idToInsert: 3 },
{ id: 6, idToInsert: 3 },
{ id: 7, idToInsert: 3 },
],
[
{ id: 8, idToInsert: 4 },
{ id: 9, idToInsert: 4 },
],
];
I'm having a bit of a hard time finding the starting point for this problem, especially because of the nested structure of the second array.
I am thankful for each hint.
this is most clear code I could come up with..
const idListToInsert = [{ idToInsert: 1 }, { idToInsert: 3 }, { idToInsert: 4 }];
const otherObjectList = [
[{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
[{ id: 5 }, { id: 6 }, { id: 7 }],
[{ id: 8 }, { id: 9 }],
];
const result = otherObjectList.map((item, index) => item.map((value) => ({
...value,
...idListToInsert[index],
})));
console.log(result);
You could map the outer array otherObjectList and their inner arrays and create a new object with additional properties.
const
idListToInsert = [{ idToInsert: 1 }, { idToInsert: 3 }, { idToInsert: 4 }],
otherObjectList = [[{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }], [{ id: 5 }, { id: 6 }, { id: 7 }], [{ id: 8 }, { id: 9 }]],
result = otherObjectList.map((a, i) => a.map(o => ({ ...o, ...idListToInsert[i] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const targetList = []
otherObjectList.forEach((subarray, index) => {
const temp = []
subarray.forEach(id => {
temp.push({id, idListToInsert[index]})
})
targetList.push(temp)
})
It is untested but it should work.