skip to Main Content

I have a string and I have a list of dictionaries in JavaScript/TypeScript and I am trying to find that string in whichever dictionary it is in (it can only be in one entry) and return a value stored in the number key in the dictionary. I am doing that by iterating through my list and comparing the value stored to my input string. All dictionary label and number entries are unique fwiw.

var myString = "ABC";
var output = 0;

const listOfDicts = [
    {label: "ABC", number: 10},
    {label: "DEF", number: 20},
    {label: "GHI", number: 30},
];

listOfDicts.forEach((e) => {
    if (e.label === myString) {
        output = e.number;
    }
});

Is this the most efficient way of assigning 10 to my output or is there a clever 1 line way of doing this that I am not aware of? Note if my structure was a Map I could just use the .get(myString) method to return the corresponding value, but I do not have a map so here we are.

2

Answers


  1. You can use the find method to make the code more concise and potentially more readable.

    const myString = "ABC";
    let output = 0;
    const listOfDicts = [
       {label: "ABC", number: 10},
       {label: "DEF", number: 20},
       {label: "GHI", number: 30}
    ];
    const found = listOfDicts.find(e => e.label === myString);
    if (found) {
        output = found.number;
    }
    console.log(output);

    The find method returns the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, it returns undefined. Therefore, checking if found is not undefined before accessing the number property is a good idea.

    If you want to do this in a single line, you can use the optional chaining operator (?.) and nullish coalescing operator (??) to handle the case where the element is not found:

    const myString = "ABC";
    const listOfDicts = [
       {label: "ABC", number: 10},
       {label: "DEF", number: 20},
       {label: "GHI", number: 30}
    ];
    const output = (listOfDicts.find(e => e.label === myString)?.number) ?? 0;
    console.log(output);
    Login or Signup to reply.
  2. Since your listOfDicts is an array of objects, you could use find method to find a matching object and if the match is found, you would get the number, like so:

    var myString = "ABC";
    let match = listOfDicts.find(x => x.label ===  myString);
    if(match) output = match.number;
    

    The find method takes a function you provide to find a match.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search