Reputation: 113
I'm trying to find the key in an object that has a third element in an array and then convert it to a number. What is the best way of doing it?
Upvotes: 0
Views: 38
Reputation: 780889
Use .find()
to find the array with at least 3 elements.
let number;
let arr = Object.values(numbersObject).find(a => a.length >= 3);
if (arr) {
number = arr[2];
}
To do it in one line, use ||
to supply a default value if no array can be found:
let number = (Object.values(numbersObject).find(a => a.length >= 3) || [,,null])[2];
Upvotes: 1