[英]ES6 destructuring to get the nth item from inner array
我的 React 項目中有一個處於我狀態的數組。 就像是 :
state = {
cats : [
{cid : 1 , value : 1}
{cid : 2 , value : 3}
{cid : 3 , value : 4}
],
curpage : 3
}
現在我想要的就是通過析構獲得數組cats
nth item
。 我試過
const { cat : {cats[id]} } = this.state;
或者
const { cats[id] } = this.state;
您可以使用具有解構的計算對象屬性來獲取第n
個數組項並將其分配給一個變量:
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)
const state = { cats : [ {cid : 1 , value : 1}, {cid : 2 , value : 3}, {cid : 3 , value : 4} ], curpage : 3 } const { cats: [,,thirdCat] } = state; console.log(thirdCat)
您可以解構索引並采用重命名的值。
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);
讓 nthID = 1; 讓 {cats} = 狀態; 讓 nthChild = 貓 [nthID];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.