EN
JavaScript - check nested object properties for null/undefined
1
answers
0
points
Let's say I have an object:
var myObject = {}
it gets populated through the course of using the app, for example:
var myObject = {
name: 'John',
metadata: {
type: 'json',
},
};
At another place in the code I want to check if myObject.metadata.type exists.
if (myObject.metadata.type) {
// do something
}
If it doesn't exists, the code will cause an error.
Also if myObject.metadata is undefined, myObject.metadata.type of course is undefined too.
That means I need to check it like this:
if (myObject.metadata) {
if (myObject.metadata.type) {
// do something
}
}
I don't think it is efficient way to check this, since the bigger objects are, the worse it gets.
Is there a better way to check conditions like this?
1 answer
0
points
1. Using optional chaining (ES 2020+)
// ONLINE-RUNNER:browser;
const myObject = {
name: 'John',
metadata: {
type: 'json',
},
};
console.log(myObject?.metadata?.type);
In dirask snippets you can find some reusable arrow functions:
2. Alternative solution
You can create a custom function:
// ONLINE-RUNNER:browser;
function getValue(object, path) {
return path.reduce(function (value, key) {
return value == null ? value : value[key];
}, object);
}
// Usage example:
var myObject = {
name: 'John',
metadata: {
type: 'json',
},
};
var metadata = getValue(myObject, ['metadata', 'type']);
console.log(metadata); // json
See also
References
0 comments
Add comment