I need help in creating a function that will transform this Array of Objects:
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 },
];
to This nested Array of Objects:
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 },
]
}
],
},
]
I have no clue how to create a new nested object document, or like creating a new nested array of "cartons" etc since I'm new to Javascript. Your help will be a stepping stone for me in understanding how to restructure such data.
Thank you.
There is not a magic solution for a problem like this, and you can make it a lot more efficient way if the output is slightly different but this is a solution:
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})
})
As you see you can check if the object is already defined inside an array with the find function. Then check if the result is undefined and create or modify.