Necesito ayuda para crear una función que transformará esta matriz de objetos:
const fromThis = [ { storageId: "S1", cartonId: "C1", bottleId: "B1", isCollected: true }, { storageId: "S1", cartonId: "C1", bottleId: "B2", isCollected: true }, { storageId: "S1", cartonId: "C1", bottleId: "B3", isCollected: false }, { storageId: "S1", cartonId: "C2", bottleId: "B4", isCollected: false }, { storageId: "S2", cartonId: "C3", bottleId: "B5", isCollected: true }, { storageId: "S2", cartonId: "C3", bottleId: "B6", isCollected: true }, { storageId: "S2", cartonId: "C4", bottleId: "B7", isCollected: false }, ];a esta matriz anidada de objetos:
const toThis = [ { storageId: "S1", totalBottles: 4, cartons: [ { cartonId: "C1", totalCollected: 2, bottles: [ { bottleId: "B1", isCollected: true }, { bottleId: "B2", isCollected: true }, { bottleId: "B3", isCollected: false }, ] }, { cartonId: "C2", totalCollected: 0, bottles: [ { bottleId: "B4", isCollected: false }, ] } ], }, { storageId: "S2", totalBottles: 3, cartons: [ { cartonId: "C3", totalCollected: 2, bottles: [ { bottleId: "B5", isCollected: true }, { bottleId: "B6", isCollected: true }, ] }, { cartonId: "C4", totalCollected: 0, bottles: [ { bottleId: "B7", isCollected: false }, ] } ], }, ]No tengo idea de cómo crear un nuevo documento de objeto anidado, o como crear una nueva matriz anidada de "cartones", etc., ya que soy nuevo en Javascript. Su ayuda será un trampolín para mí en la comprensión de cómo reestructurar dichos datos.
Gracias.
No existe una solución mágica para un problema como este, y puede hacerlo de una manera mucho más eficiente si el resultado es ligeramente diferente, pero esta es una solución:
let toThis = [] fromThis.forEach( item => { let storage = toThis.find( s => {return s.storageId === item.storageId}) if (!storage) { storage = { storageId: item.storageId, totalBottels: 0, cartons: [] } toThis.push(storage) } storage.totalBottels += 1 let carton = storage.cartons.find( c => {return c.cartonId === item.cartonId}) if (!carton) { carton = { cartonId: item.cartonId, totalCollected: 0, bottles: [] } storage.cartons.push(carton) } if (item.isCollected) carton.totalCollected += 1 carton.bottles.push({bottleId: item.bottleId, isCollected: item.isCollected}) })Como puede ver, puede verificar si el objeto ya está definido dentro de una matriz con la función de búsqueda. Luego verifique si el resultado no está definido y cree o modifique.