【发布时间】:2019-07-23 21:26:15
【问题描述】:
我有一个这样的对象
const obj = {
foo: {
bar: { // maybe null
id: 0
}
}
};
我想解构obj 得到id。如果 bar 曾经只是 undefined 或一个对象,这就足够了:
const {
foo: {
bar: {
id,
} = {},
} = {},
} = obj;
但是当bar 是null 我得到错误Cannot read property 'id' of null。
我可以做到,suggested here
const {
foo: {
bar = {},
} = {},
} = obj;
const { id } = bar || {};
但这意味着我需要将每个可为空的对象解构为单独的语句,我不希望这样做。
如果对象的值为 null,有没有办法让其默认初始化程序运行?
【问题讨论】:
标签: ecmascript-6 nested destructuring default-parameters spread-syntax