zana10
zana10

Reputation: 113

Type conversion in the object array

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

Answers (1)

Barmar
Barmar

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

Related Questions