Home > Mobile >  How to add two decimal places to an array of objects
How to add two decimal places to an array of objects

Time:03-19

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.

CodePudding user response:

    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)

CodePudding user response:

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.

  • Related