首页 > 解决方案 > 如何销毁嵌套在 ES6 对象中的两个变量

问题描述

假设我有 obj 喜欢

const user = {
 id: 339,
 name: 'Fred',
 age: 42,
 education: {
   getDegree: () => {} //function
 }
};
const {education: {getDegree}} = user;

我经常有一个用例需要从用户 obj 获取教育和学位作为参数。

我只知道如何从obj中破坏getDegree,如何获取教育变量呢?

做同样的事情,但我相信有更好的方法来做到这一点?

const {education: {getDegree}} = user;
const {education} = user;

标签: javascriptecmascript-6destructuring

解决方案


只需education在解构中列出:

const user = {
 id: 339,
 name: 'Fred',
 age: 42,
 education: {
   foo: "bar"
 }
};
const {education, education: {foo}} = user;

console.log(education);
console.log(foo);


推荐阅读