我需要解构并从该对象获取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'
如何获得子对象?
答案 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 } }
来同时获得title2
和child
。
简单到:
const obj1 = {
title: "foo",
child: {
title2: "bar"
}
};
const { title, child, child : { title2 } } = obj1