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!
CodePudding user response:
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']);
CodePudding user response:
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

