可以在对象内部使用解构赋值吗?
这是可行的
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
};发布于 2019-06-26 06:20:35
如果我没理解错的话,似乎spread syntax非常适合你的需求。
扩展语法"...“允许您将键/值对从源对象(即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);
第二个示例将源对象(即test)解构为一个对象,其中包含我们想要的键子集(a和b)。
在该表达式的作用域中(即(和)之间的所有内容),这些键都可以作为局部变量访问。我们利用这一点,并将其传递给一个新对象(即{ a, b })。因为新对象是在,之后声明的,所以它将作为表达式的结果返回。
发布于 2019-06-26 12:50:27
如果您尝试获取属性的子集,则可以使用rest运算符
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
};
const { c, ...destruct } = test;
console.log(destruct);
这会将c分配给const,并将剩余的属性分配给const析构。首先列出所有不需要的属性,然后使用rest操作符捕获剩余的属性。
也适用于数组。
const test = ['hey', 'hello', 'goodbye'];
const [ first, ...rest ] = test;
console.log(rest);
发布于 2019-06-26 14:15:47
你可以试着像这样解构数组!
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!"https://stackoverflow.com/questions/56762703
复制相似问题