Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!