Q:

How to convert the data type in JSON nodejs

I have a NodeJS Express Code that is simply passing data from client to my back end server in request-response format.
Now My client is expecting the dollar amounts in the JSON response as double datatype.
How do I do it dynamically.
For example below,
var data =   [
{
   "feeType":"Trip",
   "feeCategory":"Transaction",
   "feeAmount":0,
   "isApplicable":true,
   "isRequired":true,
   "applicableDeliveryType":"None",
   "appliedFeeAmount":0
},
{
   "feeType":"FerryFee",
   "feeCategory":"Passenger",
   "feeAmount":2,
   "isApplicable":true,
   "isRequired":false,
   "applicableDeliveryType":"None",
   "appliedFeeAmount":2
},
{
   "feeType":"WillCall",
   "feeCategory":"Service",
   "feeAmount":0,
   "isApplicable":false,
   "isRequired":false,
   "applicableDeliveryType":"Pickup",
   "appliedFeeAmount":0
},
{
   "feeType":"NotTravelling",
   "feeCategory":"Service",
   "feeAmount":0,
   "isApplicable":false,
   "isRequired":false,
   "applicableDeliveryType":"PrintAtHome",
   "appliedFeeAmount":0
},
{
   "feeType":"Pickup",
   "feeCategory":"Delivery",
   "feeAmount":0,
   "isApplicable":false,
   "isRequired":false,
   "applicableDeliveryType":"None",
   "appliedFeeAmount":0
},
{
   "feeType":"PrintAtHome",
   "feeCategory":"Delivery",
   "feeAmount":0,
   "isApplicable":false,
   "isRequired":false,
   "applicableDeliveryType":"None",
   "appliedFeeAmount":0
}

]
My Client is expecting as the number values with .0 or decimal numbers. How can I do that?

A:

Use Object.entries to loop throgh the object and use .toFixed() to add the decimal :

const data = [{
    "feeType": "Trip",
    "feeCategory": "Transaction",
    "feeAmount": 0,
    "isApplicable": true,
    "isRequired": true,
    "applicableDeliveryType": "None",
    "appliedFeeAmount": 0
  },
  {
    "feeType": "FerryFee",
    "feeCategory": "Passenger",
    "feeAmount": 2,
    "isApplicable": true,
    "isRequired": false,
    "applicableDeliveryType": "None",
    "appliedFeeAmount": 2
  }
]

const result = data.map(o => Object.entries(o).reduce((acc, [key, value]) => {
  acc[key] = typeof value.toFixed === 'function' ? value.toFixed(1) : value;
  return acc;
}, {}))
console.log(result);

Or for .. in :

const data = [{
    "feeType": "Trip",
    "feeCategory": "Transaction",
    "feeAmount": 0,
    "isApplicable": true,
    "isRequired": true,
    "applicableDeliveryType": "None",
    "appliedFeeAmount": 0
  },
  {
    "feeType": "FerryFee",
    "feeCategory": "Passenger",
    "feeAmount": 2,
    "isApplicable": true,
    "isRequired": false,
    "applicableDeliveryType": "None",
    "appliedFeeAmount": 2
  }
]
const result = [];
data.forEach(o => {
  const tempObj = {};
  for (let key in o) {
    tempObj[key] = typeof o[key].toFixed === 'function' ? o[key].toFixed(1) : o[key];
  }
  result.push(tempObj);
});
console.log(result);

