解构 javascript 中的嵌套对象 |解构二级父子对象
Destructuring Nested objects in javascript | Destructure second level parent and child Objects
我需要从该对象中解构并获取 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'
如何获取子对象?
当做 child : { child : { title2 } }
, child
不是实例化,所以你仍然可以做 { child, child : { title2 } }
来获得 title2
和 child
.
简单到:
const obj1 = {
title: "foo",
child: {
title2: "bar"
}
};
const { title, child, child : { title2 } } = obj1
child: { title2 }
只是解构 child 属性。如果您想获取 child 属性 本身,只需在语句中指定它: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);
我需要从该对象中解构并获取 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'
如何获取子对象?
当做 child : { child : { title2 } }
, child
不是实例化,所以你仍然可以做 { child, child : { title2 } }
来获得 title2
和 child
.
简单到:
const obj1 = {
title: "foo",
child: {
title2: "bar"
}
};
const { title, child, child : { title2 } } = obj1
child: { title2 }
只是解构 child 属性。如果您想获取 child 属性 本身,只需在语句中指定它: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);