Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 979
Amir Shahbabaie Avatar asked Oct 14 '25 14:10

Amir Shahbabaie


2 Answers

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)
like image 191
adiga Avatar answered Oct 17 '25 04:10

adiga


You could destructure to the index and take a renamed value.

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

console.log(item);
like image 29
Nina Scholz Avatar answered Oct 17 '25 04:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!