解构JavaScript中的嵌套对象|分解二级父对象和子对象

时间:2019-01-21 15:32:34

标签: javascript ecmascript-6 destructuring nested-object

我需要解构并从该对象获取title,child,childTitle的值

const obj1 = {
   title : 'foo',
   child : {
               title2 : 'bar'
           }
   }

let {title, child} = obj1;
console.log(title)   //'foo'
console.log(child)   //{ title : 'bar' } 

// but couldn't get child object this way

let { title , child : { title2 } } = obj1;
console.log(title)   //'foo'
console.log(child)   //unDefined
console.log(title2)  //'bar'

如何获得子对象?

2 个答案:

答案 0 :(得分:5)

child: { title2 }只是在破坏子财产。如果要提取子属性本身,只需在语句中let { title, child, child: { title2 } } = obj1;

指定即可

const obj1 = {
  title: 'foo',
  child: {
    title2: 'bar'
  }
}

let { title, child, child: { title2 } } = obj1;

console.log(title);
console.log(child); 
console.log(title2);

答案 1 :(得分:3)

在做孩子时:{ child : { title2 } }child未实例化,因此您仍然可以进行{ child, child : { title2 } }来同时获得title2child

简单到:

const obj1 = {
  title: "foo",
  child: {
    title2: "bar"
  }
};

const { title, child, child : { title2 } } = obj1