我在尝试获取其总和的数组中具有以下值。从chrome开发人员工具来看就是这样
(3) [{…}, {…}, {…}]0: {ID: 1, ProductName: " New phone 1", Price: "€ 600"}1: {ID: 3, ProductName: " New phone 2", Price: "€ 1000"}2: {ID: 4, ProductName: " New phone 3", Price: "€ 400"}length: 3__proto__: Array(0)
我想获取每个项目的价格并计算所有值的总和。我从Api获取这些值,有时可能会有更多或更少的项目。目前,这就是我获取价值的方式
function setTotalPrice() {
fetch("http://localhost:1234/api/Product")
.then(response=>response.json())
.then(data => {
data.forEach(element => {
console.log(element.Price)
});
})
}
您需要从Price
字符串中获取数字(split),然后使用reduce求和
const data = [
{ ID: 1, ProductName: 'New phone 1', Price: '€ 600' },
{ ID: 3, ProductName: 'New phone 2', Price: '€ 1000' },
{ ID: 4, ProductName: 'New phone 3', Price: '€ 400' },
];
const result = data.reduce((acc, val) => acc + parseInt(val.Price.split(' ')[1], 10), 0);
console.log(result);
console.log('€ ' + result);
如果API可以返回的浮点数Price
,则需要改用parseFloat:
const data = [
{ ID: 1, ProductName: 'New phone 1', Price: '€ 600.25' },
{ ID: 3, ProductName: 'New phone 2', Price: '€ 1000' },
{ ID: 4, ProductName: 'New phone 3', Price: '€ 400.10' },
];
const result = data.reduce((acc, val) => acc + parseFloat(val.Price.split(' ')[1]), 0);
console.log(result);
console.log('€ ' + result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句