0

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,
          });
        }
1
  • It looks almost correct, but you have schedule_ instead of schedule... (Next time try stepping through your code in a debugger, then you'd notice that cmo["schedule_" + i] is undefined and when investigating why, you'd notice that the index evaluates to schedule_1 but your object has schedule1). Same for status_so_ vs status_so. and kubikasi_ vs kubikasi. Additionally, maybe you want to not hard-code the length to 4 but instead go up without limit and instead of pushing an empty element you'd stop the loop when an item doesn't exist. Commented Nov 28, 2021 at 10:06

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.