'How to add two decimal places to an array of objects

The array looks like this:

const arr = [
    {title: 'Cat1', val1: '0', val2: '20'},
    {title: 'Cat2', val1: '0', val2: '30'},
]

I need the val1 and val2 to be converted into a number with two decimal places (eg. 0.00, 20.00), and then be able to pass the treated array (that includes everything else) in a different function.



Solution 1:[1]

    const arr = [
        {title: 'Cat1', val1: '0', val2: '20'},
        {title: 'Cat2', val1: '0', val2: '30'},
    ]

    const result = arr.map(a1 => {
        a1.val1 += ".00"
        a1.val2 += ".00"
        return a1
    })

    console.log(result)

Solution 2:[2]

const arr = [{
    title: 'Cat1',
    val1: '0',
    val2: '20'
  },
  {
    title: 'Cat2',
    val1: '0',
    val2: '30'
  },
]

function print(data) {
  console.log(data);
}

function convertToDecimal(data) {
  let num = parseInt(data);
  return num.toFixed(2);
}
const converteedArray = arr.map((obj1) => {

  if (obj1.val1) {
    obj1.val1 = convertToDecimal(obj1.val1);
  }
  if (obj1.val2) {
    obj1.val2 = convertToDecimal(obj1.val2);
  }
  return obj1;
});
print(converteedArray);

Please check the above working example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dinesh oz
Solution 2