[英]Push only one type of item in array
我希望能够从我的数组中提取在一个特定位置购买的物品的值。 我希望能够提取该值并将其放入一个单独的数组中,例如在下面发布的数组中,我希望能够只获取项目类型 Food 的价格并将其推入一个单独的数组中,如何我这样做?
const array = [
{ Type: "Food", Price: "100" },
{ Type: "Entertainment", Price: "200" },
{ Type: "Food", Price: "80" },
{ Type: "Entertainment", Price: "150" }
];
有没有更简单的方法来获得食物类型的总价格?
您将希望将数据减少为一个总和。 如果它们的键等于“食物”,您只会添加到总和(运行总数)。
您从零开始,并添加已解析的 integer(因为您不关心小数)价格每个具有“食物”键的项目。
编辑: reducer的逻辑如下:
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));
使用forEach()迭代数组并添加给定type
的价格以获得总数。
使用Number()将价格从字符串转换为数字。 即使价格有小数,这也有效。
const array = [ { Type: "Food", Price: "100" }, { Type: "Entertainment", Price: "200" }, { Type: "Food", Price: "80" }, { Type: "Entertainment", Price: "150" } ]; function getTotalPrice(array, type) { let total = 0; array.forEach(item => { if (item.Type === type) { total += Number(item.Price); } }); return total; } console.log(getTotalPrice(array, "Food"));
或使用reduce() 。
const array = [ { Type: "Food", Price: "100" }, { Type: "Entertainment", Price: "200" }, { Type: "Food", Price: "80" }, { Type: "Entertainment", Price: "150" } ]; function getTotalPrice(array, type) { return array.reduce((total, item) => { if (item.Type === type) { total += Number(item.Price); } return total; }, 0); return total; } console.log(getTotalPrice(array, "Food"));
您必须首先使用要操作的类型过滤数组。 这将为您提供一个仅包含您想要的类型的新数组,然后您可以将每个项目的价格相加。
foodArray = array.filter(a => a.Type === "Food");
var totalPrice = 0;
foodArray.forEach(food => totalPrice = totalPrice + food.Price);
请注意,如果“价格”是一个字符串,您应该首先将其转换为一个数字。 如果你不这样做,你最终会得到所有价格的串联,而不是总和。
您可以使用 javascript function filter()
,并使用 function 作为回调使用类型。
const array = [
{ Type: "Food", Price: "100" },
{ Type: "Entertainment", Price: "200" },
{ Type: "Food", Price: "80" },
{ Type: "Entertainment", Price: "150" }
];
let type = 'Food';
var found = array.find(findType(type));
function findType(type) {
return (item) => item.Type === type;
}
console.log(found);
// Object { Type: "Food", Price: "100" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.