Here’s what I mean, I want to do something that is a combination of :
const {b: {c}} = a;
and
const {b={c:0}} = a;
I know I can break them apart like:
const a = {};
const {b={c:0}} = a;
const {c} = b;
console.log(c); //will get 0
But is there anyway to do them in a single statement? Something like (below code doesn’t work):
const a = {};
const{b:{c}={c:0}} = a;
console.log(c); // Hoping to get 0
>Solution :
Assuming you want to get a default c value, you could use a nested default value and destructuring.
const
getC = a => {
const { b: { c = 0 } = {} } = a;
return c;
};
console.log(getC({}));
console.log(getC({ b: {} }));
console.log(getC({ b: { c: 42 } }));