简体   繁体   English

仅推送数组中的一种类型的项目

[英]Push only one type of item in array

I want to be able to extract the values of the items bought at one specific location from my array.我希望能够从我的数组中提取在一个特定位置购买的物品的值。 I want to be able to extract the value and put it into a seperate array, for example in the array posted below, I want to be able to get only the price for the item type Food and push it into a seperate array, how can I do that?我希望能够提取该值并将其放入一个单独的数组中,例如在下面发布的数组中,我希望能够只获取项目类型 Food 的价格并将其推入一个单独的数组中,如何我这样做?

const array = [
    { Type: "Food", Price: "100" },
    { Type: "Entertainment", Price: "200" },
    { Type: "Food", Price: "80" },
    { Type: "Entertainment", Price: "150" }
];

Is there any easier way to get the total price of type Food?有没有更简单的方法来获得食物类型的总价格?

You will want to reduce the data as a single sum.您将希望将数据减少为一个总和。 You will only add to the sum (running total) if they key equals "Food".如果它们的键等于“食物”,您只会添加到总和(运行总数)。

You start at zero, and add the parsed integer (since you do not care about decimals) price each item that has a key of "Food".您从零开始,并添加已解析的 integer(因为您不关心小数)价格每个具有“食物”键的项目。

Edit: The logic of the reducer is as follows:编辑: 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' }));


If you want to handle floating values...如果要处理浮动值...

You can use parseFloat instead of parseInt and format the number with toFixed(2) .您可以使用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));

Use forEach() to iterate on array and add the prices of given type to get the total.使用forEach()迭代数组并添加给定type的价格以获得总数。

Use Number() to convert the price from string to number.使用Number()将价格从字符串转换为数字。 This works even if the price has decimals.即使价格有小数,这也有效。

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

Or use reduce() .或使用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"));

You will have to first filter the array with the type you want to manipulate.您必须首先使用要操作的类型过滤数组。 This will give you a new array with only the type you want, which you can then just sum the price of each item.这将为您提供一个仅包含您想要的类型的新数组,然后您可以将每个项目的价格相加。

foodArray = array.filter(a => a.Type === "Food");
var totalPrice = 0;
foodArray.forEach(food => totalPrice = totalPrice + food.Price);

Please note that if "Price" is a string, you should first cast that into a number.请注意,如果“价格”是一个字符串,您应该首先将其转换为一个数字。 If you don't do that you will end up with a concatenation of all Prices, instead of a sum.如果你不这样做,你最终会得到所有价格的串联,而不是总和。

You could use javascript function filter() , and use a function as callback using with the type.您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM