簡體   English   中英

僅推送數組中的一種類型的項目

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM