'how to check for a string value if it exists in a list of dictionary (Javascript)?

I have the following List of strings:

books = ['alpha', 'betta', 'other']

and the following List of Dict:

guide = [ 
          {'name':'alpha', 'id':'1'},
          {'name':'betta', 'id':'2'},
          {'name':'other', 'id':'3'},
          ...
          ...
        ]

I receive a list of books as an input from API call, and now i need to map the book name to its corresponding id (for something I need it). For example, if I get "betta" as in input, I need to get its id which is "2" in this case in order to use it somewhere else.

What is the best practice to do so? Is there a mapper or something similar that can help?

I know I can do this by creating 2 For loops and compare the input string (betta) with the element['name'] for each element in guide, but the guide I have is really big and i will need to loop through a bunch of data.

Any help would be appreciated! Thank you!



Solution 1:[1]

What I would suggest you to do is the following

const guide = new Map([
    ["alpha", 1],
    ["betta", 2],
    ["other", 3]
]);

console.log(guide.get('betta')); // 2

This is the best approach for performance and it is also more readable and less resource consuming.

EDIT:

benchmark loop vs map, and the gap is bigger with bigger collection

enter image description here

Solution 2:[2]

I like the answers already provided by @CertainPerformance and @AdrienDePeretti.

Here's another approach. I wonder which performs best!

const guide = [ {'name':'alpha', 'id':'1'}, {'name':'betta', 'id':'2'}, {'name':'other', 'id':'3'}];
const obj = guide.reduce((acc,{name,id}) => ({...acc,[name]:id}),{});

console.log(obj['betta']);

Solution 3:[3]

There is a find method in JS for this purpose:

const guide = [ {'name':'alpha', 'id':'1'}, {'name':'betta', 'id':'2'}, {'name':'other', 'id':'3'}];
const idsByName = (targetName) => 
  guide.find(({ name }) => name === targetName)?.id;

console.log(idsByName('betta'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 PeterKA
Solution 3