0

Is there a way to destruct the last item in an array if I don't know it's length in advance?

I have:

let response = {
  data: [
    { name: 'item1', level: 1 },
    { name: 'item2', level: 10 },
    { name: 'item3', level: 11 }
  ]
};

And I would like to get name and level of the last item in the array.

I know I can get an item with a specific index, for instance:

const {data: [,, {name, level}]} = response

But as the data array has a various length, it doesn't suit.

Yann
  • 2,426
  • 1
  • 16
  • 33

1 Answers1

1

What about getting the last element of the array and then destructure it?

let response = {
  data: [
    { name: 'item1', level: 1 },
    { name: 'item2', level: 10 },
    { name: 'item3', level: 11 }
  ]
};

const {name, level} = response.data[response.data.length - 1];
console.log(name, level);
Shidersz
  • 16,846
  • 2
  • 23
  • 48