This question already has an answer here:
- Access Javascript nested objects safely 6 answers
I'm looking for some good strategies for avoiding errors in JavaScript when using dot notation to call the children of children in objects that may or may not exist.
At the bottom of the code snippet below is an example of a solution that works, but is inelegant (at best).
It would be great to see some native JavaScript solutions or even external libraries that can help avoid this kind of error.
const object1 = {
foo: {
bar: {
baz: 'payload'
}
}
};
const object2 = {};
const array = [object1, object2];
// this will fail on object2 because obj.foo is undefined
array.forEach(obj => {
if (obj.foo.bar.baz) {
console.log(obj.foo.bar.baz);
} else {
console.log('undefined');
}
}
);
// this will work, but it's horrible to write all those nested if statements.
array.forEach(obj => {
if (obj) {
if (obj.foo) {
if (obj.foo.bar) {
if (obj.foo.bar.baz) {
console.log(obj.foo.bar.baz);
}
}
}
} else {
console.log('undefinded');
}
}
);
Just to share my two cents:
Some time ago I made a function that allowed to safely access deep properties in javascript using proxies:
Also, I wrote an article on this for further reference.
No sure if that's enough of an improvement but you can use a single if statement with the following condition:
This will check if
obj.foo.bar.baz
exists.You could chain all checks with logical AND
&&
.For an automatic check, you could take an array of keys and return either the value or
undefined
.Lodash already did it for us: https://lodash.com/docs#get