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;
You can use the computed object property with destructuring to get the n
th 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)
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);
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