解构es6但传递动态变量
Destructuring of es6 but passing dynamic variable
说我的state
是这样的:
{
item:{
a:'a',
b:'b'
}
}
然后我可以通过以下方式从项目中提取 a
:
const { a } = this.state.item
但可以使用 es6
的 {}
动态拉取 ?
例如const { variable } = this.state.item
,其中variable
可以是a
或b
。
与 4castle pointet out, you could use Computed object property names and destructuring 一样,带有额外的 key/value 对变量用于解构。
var object = { item: { a: 'a0', b: 'b0' } },
key = 'b',
value;
({ [key]: value } = object.item);
console.log(value);
说我的state
是这样的:
{
item:{
a:'a',
b:'b'
}
}
然后我可以通过以下方式从项目中提取 a
:
const { a } = this.state.item
但可以使用 es6
的 {}
动态拉取 ?
例如const { variable } = this.state.item
,其中variable
可以是a
或b
。
与 4castle pointet out, you could use Computed object property names and destructuring 一样,带有额外的 key/value 对变量用于解构。
var object = { item: { a: 'a0', b: 'b0' } },
key = 'b',
value;
({ [key]: value } = object.item);
console.log(value);