Quiero asignar la clave de una matriz a otra matriz anidada. Ambas matrices tienen la misma longitud.
Antes:
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 }], ];Objetivo:
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 }, ], ];Me está costando un poco encontrar el punto de partida de este problema, especialmente debido a la estructura anidada de la segunda matriz.
Estoy agradecido por cada pista.
este es el código más claro que pude encontrar ...
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);Puede mapear la matriz externa otherObjectList y sus matrices internas y crear un nuevo objeto con propiedades adicionales.
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) })No está probado, pero debería funcionar.