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?
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With