gpt4 book ai didi

javascript - nodejs中JSON数据类型的转换方法

转载 作者:行者123 更新时间:2023-11-30 11:01:13 24 4
gpt4 key购买 nike

我有一个 NodeJS Express 代码,它只是以请求-响应格式将数据从客户端传递到我的后端服务器。现在我的客户期望 JSON 响应中的美元金额为 double 据类型。我如何动态地做到这一点。例如下面,

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
}

]

我的客户期望使用 .0 或十进制数字作为数值。我该怎么做?

最佳答案

使用 Object.entries 遍历对象并使用 .toFixed() 添加小数点:

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);

或者 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);

关于javascript - nodejs中JSON数据类型的转换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com