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,
});
}
schedule_instead ofschedule... (Next time try stepping through your code in a debugger, then you'd notice thatcmo["schedule_" + i]isundefinedand when investigating why, you'd notice that the index evaluates toschedule_1but your object hasschedule1). Same forstatus_so_vsstatus_so. andkubikasi_vskubikasi. Additionally, maybe you want to not hard-code the length to4but instead go up without limit and instead of pushing an empty element you'd stop the loop when an item doesn't exist.