How to destructing two variables that are nested in an object in ES6 [duplicate]

问题: This question already has an answer here: Destructure a nested object, but keep a reference to the nested object 2 answers Destructuring nested objects...

问题:

Let's say I have obj like

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

I often have a use case that needs to get both education and degree as parameter from user obj.

I only know how to destruct getDegree from obj, what to do to get the education variable as well?

something to do the same thing, but I believe there is a better way to do this?

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

回答1:

Just list education in the destructure as well:

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

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

  • 发表于 2019-02-13 23:42
  • 阅读 ( 210 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除