Search code examples
javascriptecmascript-6destructuring

ES6 destructuring to get the nth item from inner array


I have an array in my state in my React project. something like :

state = {
   cats : [
      {cid : 1 , value : 1}
      {cid : 2 , value : 3}
      {cid : 3 , value : 4}
   ],
   curpage : 3
}

now all I want is to get nth item of the array cats with destructring. I tried

const { cat : {cats[id]} } = this.state;

or

 const { cats[id] } = this.state;

Solution

  • You can use the computed object property with destructuring to get the nth array item and assign it to a variable:

    const state = {
       cats : [
          {cid : 1 , value : 1},
          {cid : 2 , value : 3},
          {cid : 3 , value : 4}
       ],
       curpage : 3
    }
    
    const n = 2;
    
    const { cats: { [n]: nthCat} } = state;
    
    console.log(nthCat)

    Or, if n is small and you know it beforehand, you could ignore the values you don't need:

    const state = {
       cats : [
          {cid : 1 , value : 1},
          {cid : 2 , value : 3},
          {cid : 3 , value : 4}
       ],
       curpage : 3
    }
    
    const { cats: [,,thirdCat] } = state;
    
    console.log(thirdCat)