![](/img/trans.png)
[英]"Must use destructuring state assignment": How to destructure from object and place on property inside object literal
[英]How to use a destructuring assignment inside an object
是否可以在对象内部使用解构分配?
这有效
const test = {a: 'hey', b: 'hello'}
const {a,b} = test;
const destruct = {
a,
b
};
想这样做
const test = {a: 'hey', b: 'hello'}
// something like this
const destruct = {
{a,b}: test
};
const destruct = {
{a}: test,
{b}: test
};
如果我理解正确,那么spread语法似乎很适合您的需求。
传播语法“ ...
”允许您将键/值对从源对象(即test
)“传播”到目标对象(即destruct
):
const test = { a: 'hey', b: 'hello', c: 'goodbye' } const destruct = { // {a,b}: test <-- invalid syntax ...test // equivalent using the "spread" syntax }; console.log(destruct)
此外,如果您想从源对象中选择键的子集并将其散布到目标对象中,则可以通过以下方法实现:
const test = { a: 'hey', b: 'hello', c: 'goodbye' } /* Spread subset of keys from source object to target object */ const welcomeOnly = { ...({ a, b } = test, { a, b }) } console.log('exclude goodbye, show welcomes only:', welcomeOnly);
第二个示例通过使用我们想要的键子集( a
和b
)将源对象(即test
)分解为一个对象而工作。
在该表达式(即与一切的范围(
和)
),这些键是局部变量进行访问。 我们利用这一点,并将它们传递给新对象(即{ a, b }
)。 由于新对象是在,
之后声明的,
因此将其作为表达式的结果返回。
如果您尝试获取属性的子集,则可以使用rest运算符
const test = { a: 'hey', b: 'hello', c: 'goodbye' }; const { c, ...destruct } = test; console.log(destruct);
这将c分配给const,将剩余的属性分配给const析构函数。 首先列出所有不需要的属性,然后用其余运算符捕获剩余的属性。
也适用于数组。
const test = ['hey', 'hello', 'goodbye']; const [ first, ...rest ] = test; console.log(rest);
您可以尝试像这样工作以破坏数组!
let abc = {
a: 'hello',
b: 'hey',
c: 'hi, there!'
}
let {a: x, b:y, c:z} = abc;
console.log(x,y,z)
// "hello"
"hey"
"hi, there!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.