How do I fix empty property values in an array of objects with different value type in javascript?



I have an array of objects returned from database. Goal is to calculate the percentage of marks for each id. For some objects marks are stored in array whereas for some it is just a normal variable.

const data=[
  {
    "Id": 1,
    "marks": [40.25],   
  },
  {
    "Id": 7,
    "marks": [70,80],
  },
  {
    "Id": 2,
    "marks": 60,
  },
  {
    "Id":5,
    "marks": [],
  }
]
let res=[]
for(var i=0;i<data.length;i++)
{
    let rbp=[]
    dbp=data[i].marks
    for(var j=0;j<dbp.length;j++)
    {
        const tmp=(parseFloat(dbp[j])/80)*(90/100)
        rbp.push(tmp)
    }
    console.log(rbp)
    res.push({
        iD:data[i].Id,
        PERCENTAGE:rbp
    })
}
console.log(res)

the above code generates the following output

[ { iD: 1, PERCENTAGE: [ 0.45281250000000006 ] },
  { iD: 7, PERCENTAGE: [ 0.7875, 0.9 ] },
  { iD: 2, PERCENTAGE: [] },
  { iD: 5, PERCENTAGE: [] } ]

Percentage of marks for the penultimate object just returns an empty array. I tried getting the typeof marks but it returns object for both array and non array. How do I fix this?

Answer

You can standardised the marks to array by checking if marks is array using Array.isArray() and convert number to array. Then you can use your existing logic.

const data = [{
    "Id": 1,
    "marks": [40.25],
  },
  {
    "Id": 7,
    "marks": [70, 80],
  },
  {
    "Id": 2,
    "marks": 60,
  },
  {
    "Id": 5,
    "marks": [],
  }
]
let res = [];
for (var i = 0; i < data.length; i++) {
  let rbp = [];
  const dbp = Array.isArray(data[i].marks) ? data[i].marks: [data[i].marks];
  for (var j = 0; j < dbp.length; j++) {
    const tmp = (dbp[j] / 80) * (90 / 100);
    rbp.push(tmp);
  }
  res.push({
    ID: data[i].Id,
    PERCENTAGE: rbp
  })
}
console.log(res)

You can also use functional style to accomplish it.

const data=[ { "Id": 1, "marks": [40.25], }, { "Id": 7, "marks": [70,80], }, { "Id": 2, "marks": 60, }, { "Id":5, "marks": [], } ],
      result = data.map(o => {
        const marks = Array.isArray(o.marks) ? o.marks: [o.marks];
        const percentage = marks.map((mark) => (mark/80) * (90/100));
        return { ID: o.id, PERCENTAGE: percentage };
      });
console.log(result);


Source: stackoverflow