0

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?

3
  • Why do you want to write it one line? What's your objective? Commented Oct 26, 2020 at 20:00
  • So how is this different than stackoverflow.com/questions/64542615/… Commented Oct 26, 2020 at 20:09
  • You really need to start selecting answers to your questions. You asked 10 questions, zero have selected answers. Commented Oct 26, 2020 at 20:11

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.