Object destructuring solution for long arrays?

后端 未结 2 1064
天涯浪人
天涯浪人 2020-12-11 18:03

Looking at this code:

let lecture = {
    id: 2,
    title: \"MyTitle\",
    topics: [
    {
        title: \"John\",
        age: 1
    },
    {
        tit         


        
相关标签:
2条回答
  • 2020-12-11 18:03

    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.

    0 讨论(0)
  • 2020-12-11 18:21

    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];
    
    0 讨论(0)
提交回复
热议问题