Home > OS >  convert object to array of object
convert object to array of object

Time:11-28

I have data from backend like this :

 const fetchResult = { 
            cmo: 'integrated', 
            schedule1: '2021-08-12', 
            schedule2: '2021-09-20', 
            kendaraan: {}, 
            kubikasi1: 207000, 
            kubikasi2: 20000,
            status_so1: true,
            status_so2: false,
}

what i expected :

const result = [
  {
    schedule: value,
    kubikasi: value,
    status_so: true
  },
  {
    schedule: value,
    kubikasi: value,
    status_so: false
  },
]

basically i want to format json from backend to array of objects and i want to group it, based on what expected result. and data for example like schedule from the api can be dynamic like schedule6.

what i already tried

for (let i = 1; i <= 4; i  ) {
        if (cmo["schedule_"   i]) {
          data.push({
            schedule: cmo["schedule_"   i],
            namakendaraan: cmo["namakendaraan"   i],
            kendaraan: cmo["kendaraan"   i],
            totalCarton: cmo["totalCarton"   i],
            tonase: cmo["tonase_"   i],
            totalTonaseKendaraan: cmo["totalTonaseKendaraan"   i],
            totalPercentaseTonaseOrder: cmo["totalPercentaseTonaseOrder"   i],
            kubikasi: cmo["kubikasi_"   i],
            totalKubikasiKendaraan: cmo["totalKubikasiKendaraan"   i],
            totalPercentaseKubikasiOrder:
              cmo["totalPercentaseKubikasiOrder"   i],
            nomor_so: cmo["nomor_so_"   i],
            status_so: cmo["status_so_"   i],
          });
        } else {
          data.push({
            schedule: null,
            namakendaraan: null,
            kendaraan: null,
            totalCarton: null,
            tonase: null,
            totalTonaseKendaraan: null,
            totalPercentaseTonaseOrder: null,
            kubikasi: null,
            totalKubikasiKendaraan: null,
            totalPercentaseKubikasiOrder: null,
            nomor_so: null,
            status_so: null,
          });
        }

CodePudding user response:

You can reduce the object's entries to a Map. For each entry, take the key and the number (idx) . If no number, skip by returning the accumulator (the Map). If idx exists, add/update the object in the Map:

const fetchResult = {"cmo":"integrated","schedule1":"2021-08-12","schedule2":"2021-09-20","kendaraan":{},"kubikasi1":207000,"kubikasi2":20000,"status_so1":true,"status_so2":false}

const result = Array.from(Object.entries(fetchResult)
  .reduce((acc, [k, v]) => {
    const [key, idx = null] = k.split(/([0-9] $)/)
    
    return idx === null
      ? acc
      : acc.set(idx, { ...acc.get(idx), [key]: v })
  }, new Map()).values())
  
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Group all entries of the object based on the number, reduce to an array of array of array. Then map to array of objects.

const fetchResult = { cmo: 'integrated', schedule1: '2021-08-12', schedule2: '2021-09-20', kendaraan: {}, kubikasi1: 207000, kubikasi2: 20000,status_so1: true,status_so2: false,}


const result = Object.entries(fetchResult).reduce((a,c)=>{
    if(parseInt(c[0][c[0].length-1])>0){
        const ind = parseInt(c[0][c[0].length-1])-1
        const push = [c[0].substring(0,c[0].length-1),c[1]]
        !a[ind]?(a[ind]=[],a[ind].push(push)):a[ind].push(push)
    }
    return a
},[]).map(el=>Object(Object.fromEntries(el)))

console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related