Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object destructuring solution for long arrays?

Looking at this code:

let lecture = {
  id: 2,
  title: "MyTitle",
  topics: [
    {
      title: "John",
      age: 1
    },
    {
      title: "John2",
      age: 2
    },
    {
      title: "John3",
      age: 3
    }
  ]
}

I want to extract the main title property and the third age in the array (via object destructuring)

I can do it via :

let { title:lectureTitle , topics:[,,{age:thirdAge}]} = lecture;
console.log(lectureTitle,thirdAge);//MyTitle 3

Question

But what if the array has 100 items and I want the 99'th age ?

How would then I do it ? Does object destructuring offer a solution for that?

like image 786
Royi Namir Avatar asked Oct 28 '15 17:10

Royi Namir


2 Answers

But what if the array has 100 items and I want the 99'th age ?

Arrays are objects, so this will do:

let {title: lectureTitle, topics: {98: {age: thirdAge}}} = lecture;

Note however that the [...] type of destructuring works with any iterable, whereas {...} only works with objects (and therefore arrays). For the above solution to work with arbitrary iterables you will have to spread the iterable and wrap it with an array.

let {title: lectureTitle, topics: {98: {age: thirdAge}}} = [...lecture];
like image 165
Felix Kling Avatar answered Sep 22 '22 04:09

Felix Kling


Probably too late to reply this,

const index = 65
const {title: lectureTitle, topics: {[index]: {age: thirdAge}}} = lecture

because in real life we normally would be using dynamic indices for arrays to destructure, square brackets instead of numbers or just { index: {age}} doesn't work.

like image 30
Krishna Avatar answered Sep 22 '22 04:09

Krishna