8

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?

Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 4
    Destructuring does not seem like a good fit for what you want to do. Unless you are dead set on it, why not just access at the indexes you want? – Nick Tomlin Oct 28 '15 at 17:18
  • Nick , in order for me to know when should i use stuff , i got to know their power and limitations . It's a learning purpose ( object destructering) – Royi Namir Oct 28 '15 at 17:20
  • @RoyiNamir Clearly this is not a good fit for destructuring. When the alternative is cleaner code (in this case, good old-fashioned array access), you're probably better off not being clever. – ssube Oct 28 '15 at 17:21
  • In order to use array destructuring you should know exactly which array element you want to extract (namely its index), and you should know it at coding-time (not at run-time). It's a common case when you're dealing with small static arrays. But large arrays are seldom static, so situation like that seems extremely unlikely to me. – Leonid Beschastny Oct 28 '15 at 17:37

2 Answers2

16

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];
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • But how to set value for a variable that already exists ? `let item = 'x'; [,item] = array` works but `let item = 'x'; { 1: item } = array` doesn't work since it doesn't have const or let keyword. – Yohan Dahmani Nov 20 '20 at 09:35
  • 1
    @YohanDahmani: You need to wrap the assignment in parenthesis. See https://stackoverflow.com/q/27386234/218196 – Felix Kling Nov 20 '20 at 10:05
2

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.

Krishna
  • 673
  • 3
  • 6
  • 21