从对象中解构一组变量



我有一个Javascript对象如下:

profile= {
profilePicture: null,
username: null,
age: null,
gender: null,
followedBy: [],
following: [],
aboutMe: null
}

我想把所有的属性解构成变量,像这样:

const {userName, age, gender, followedBy, following, aboutMe} = profile

假设将来这个配置文件对象将有30个属性,我如何遍历所有属性,而不是一个接一个地键入它们?我在想这样的事情

const {userName, age, ...rest} = profile

而不是rest变量,它实际上给了我所有其他属性名作为我可以使用的独立变量名。我尝试了

const {...Object.keys(profile)} = profile

但是不能用

任何想法?

只需将大括号更改为方括号

例如

const [userName, age, gender, followedBy, following, aboutMe] = profile
const [userName, age, ...rest] = profile

最新更新