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?
-
Why do you want to write it one line? What's your objective?Randy Casburn– Randy Casburn2020-10-26 20:00:14 +00:00Commented Oct 26, 2020 at 20:00
-
So how is this different than stackoverflow.com/questions/64542615/…epascarello– epascarello2020-10-26 20:09:55 +00:00Commented Oct 26, 2020 at 20:09
-
You really need to start selecting answers to your questions. You asked 10 questions, zero have selected answers.epascarello– epascarello2020-10-26 20:11:13 +00:00Commented Oct 26, 2020 at 20:11
Add a comment
|
1 Answer
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];