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
You can use the
find
method to make the code more concise and potentially more readable.The
find
method returns the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, it returnsundefined
. Therefore, checking iffound
is notundefined
before accessing thenumber
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:Since your
listOfDicts
is an array of objects, you could usefind
method to find a matching object and if the match is found, you would get the number, like so:The find method takes a function you provide to find a match.