ES6解构以从内部数组中获取第n个项目
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;
您可以解构索引并取一个重命名的值。
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);
您可以使用 computed object property with destructuring 获取第 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)
或者,如果 n
很小并且你事先知道,你可以 ignore the values 你不需要:
const state = {
cats : [
{cid : 1 , value : 1},
{cid : 2 , value : 3},
{cid : 3 , value : 4}
],
curpage : 3
}
const { cats: [,,thirdCat] } = state;
console.log(thirdCat)
let nthID = 1; let {cats} = state; let nthChild = cats[nthID];
我的 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;
您可以解构索引并取一个重命名的值。
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);
您可以使用 computed object property with destructuring 获取第 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)
或者,如果 n
很小并且你事先知道,你可以 ignore the values 你不需要:
const state = {
cats : [
{cid : 1 , value : 1},
{cid : 2 , value : 3},
{cid : 3 , value : 4}
],
curpage : 3
}
const { cats: [,,thirdCat] } = state;
console.log(thirdCat)
let nthID = 1; let {cats} = state; let nthChild = cats[nthID];