9

我需要从这个对象中解构并获取 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'

我怎么能得到子对象?

4

2 回答 2

17

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);

于 2019-01-21T15:37:11.353 回答
3

当做 child :{ child : { title2 } }时,child不是实例化,所以你仍然{ child, child : { title2 } }可以同时得到title2and child

很简单:

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

const { title, child, child : { title2 } } = obj1  
于 2019-01-21T15:34:02.137 回答