我希望能够从我的数组中提取在一个特定位置购买的商品的价值。我希望能够提取值并将其放入一个单独的数组中,例如在下面发布的数组中,我希望仅获取食品类型食品的价格并将其推入一个单独的数组中,我是那样吗
const array = [
{ Type: "Food", Price: "100" },
{ Type: "Entertainment", Price: "200" },
{ Type: "Food", Price: "80" },
{ Type: "Entertainment", Price: "150" }
];
有没有更简单的方法来获取食品类型的总价格?
最佳答案
您将需要减少数据的总和。如果它们的键等于“食物”,则只将它们加起来(运行总额)。
您从零开始,并为每个键为“食物”的商品添加解析后的整数(因为您不关心小数)的价格。
编辑:减速器的逻辑如下:
TOTAL + (DOES_KEY_MATCH? YES=PARSED_VALUE / NO=ZERO);
const array = [
{ Type: "Food", Price: "100" },
{ Type: "Entertainment", Price: "200" },
{ Type: "Food", Price: "80" },
{ Type: "Entertainment", Price: "150" }
];
/**
* Returns the sum of targeted values that match the key.
* @param data {object[]} - An array of objects.
* @param key {string} - The value of the key that you want to match.
* @param options.keyField [key] {string} - The key field to match against.
* @param options.valueField [value] {string} - The value of the matching item.
* @return Returns the sum of all items' values that match the desired key.
*/
function calculateTotal(data, key, options) {
let opts = Object.assign({ keyField: 'key', valueField: 'value' }, options || {});
return data.reduce((sum, item) => {
return sum + (item[opts.keyField] === key ? parseInt(item[opts.valueField], 10) : 0);
}, 0);
}
console.log('Total cost of Food: $' + calculateTotal(array, 'Food', {
keyField: 'Type',
valueField: 'Price'
}));
如果要处理浮点值...
您可以使用
parseFloat
代替parseInt
,并使用toFixed(2)
格式化数字。const array = [
{ Type: "Food", Price: "100" },
{ Type: "Entertainment", Price: "200" },
{ Type: "Food", Price: "80" },
{ Type: "Entertainment", Price: "150" }
];
function calculateTotal(data, key, options) {
let opts = Object.assign({ keyField : 'key', valueField : 'value' }, options || {});
return data.reduce((sum, item) => {
return sum + (item[opts.keyField] === key ? parseFloat(item[opts.valueField]) : 0);
}, 0);
}
console.log('Total cost of Food: $' + calculateTotal(array, 'Food', {
keyField : 'Type',
valueField : 'Price'
}).toFixed(2));
关于javascript - 仅插入数组中的一种类型的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58651028/