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 :
Turn the array of objects into a mapping of names to IDs first.
const guide = [ {'name':'alpha', 'id':'1'}, {'name':'betta', 'id':'2'}, {'name':'other', 'id':'3'}];
const idsByName = Object.fromEntries(guide.map(({ name, id }) => [name, id]));
console.log(idsByName['alpha']);