簡體   English   中英

從鍵數組中獲取對象的值

[英]Getting values of an object from an array of keys

有一個對象保存雜貨店的商品和價格:

let groceryStore = {
    'Banana' : .25,
    'Apple' : .30,
    'Lettuce' : 1.20,
    'Onion' : .15,
    'Celery' : 1.15,
    'Garlic' : 1.00,
    'Tomato' : .50
}

您有一組鍵:

let groceryList = ['Tomato', 'Lettuce', 'Garlic', 'Onion']

我現在需要找到數組(groceryList)中鍵的所有值的總和。

要獲取一個數組,並將其縮減為另一個值,您通常可以使用恰當命名的Array.reduce() 通常要對一個數字數組求和,您可以減少數組,並將每個數字添加到累加器(示例中的sum ):

arrayOfNumbers.reduce((sum, num) => sum + num, 0)

在您的情況下,減少鍵數組,並使用key從對象中獲取值:

 const groceryStore = { 'Banana': .25, 'Apple': .30, 'Lettuce': 1.20, 'Onion': .15, 'Celery': 1.15, 'Garlic': 1.00, 'Tomato': .50 } const groceryList = ['Tomato', 'Lettuce', 'Garlic', 'Onion'] const result = groceryList.reduce((sum, key) => sum + groceryStore[key], 0) console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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