Warm tip: This article is reproduced from stackoverflow.com, please click
arrays javascript lookup

How to apply lookup to array in Javascript?

发布于 2020-04-23 13:42:46

How can I apply an array to a lookup dictionary in Javascript? Example:

lookup = {"milk": 1, "water": 2, "soda": 3};
my_array = ["milk", "milk", "water", "milk", "soda"];

my_array.??? // This should give [1, 1, 2, 1, 3]

I've tried my_array.map(lookup) and I get #<Object> is not a function. Same with .filter(), .apply() and the other obvious candidates.

Questioner
user1717828
Viewed
22
mickl 2020-02-10 10:32

You need array.map() but you have to specify a function which transforms single my_array element:

let lookup = {"milk": 1, "water": 2, "soda": 3};
let my_array = ["milk", "milk", "water", "milk", "soda"];

let result = my_array.map(x => lookup[x]);
console.log(result);