Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading