When accessing value of a nested JSON object key, we need to check for existence of parent keys to prevent undefined key errors.
Given this:
var obj = {
aaa: {
bbb: {
ccc: {
ddd: 'ok'
}
}
}
};
// #1 cause error if any of the parent key is not defined (e.g. aaa, bbb, ccc)
const ddd = obj.aaa.bbb.ccc.ddd || 'none';
// #2 this works but lots of repetition
const ddd = obj.aaa && obj.aaa.bbb && obj.aaa.bbb.ccc && obj.aaa.bbb.ccc.ddd || 'none';
In the example above, #1
will not work if aaa, bbb, or ccc is not defined.
#2
works but you see the repetition of ancestor keys.
Q: Is there a JavaScript/ES6 syntax to simplify this or we need to write/use a custom function?