EN
JavaScript - check nested object properties for null/undefined
1 answers
0 points
Let's say I have an object:
xxxxxxxxxx
1
var myObject = {}
it gets populated through the course of using the app, for example:
xxxxxxxxxx
1
var myObject = {
2
name: 'John',
3
metadata: {
4
type: 'json',
5
},
6
};
At another place in the code I want to check if myObject.metadata.type
exists.
xxxxxxxxxx
1
if (myObject.metadata.type) {
2
// do something
3
}
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:
xxxxxxxxxx
1
if (myObject.metadata) {
2
if (myObject.metadata.type) {
3
// do something
4
}
5
}
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+)
xxxxxxxxxx
1
const myObject = {
2
name: 'John',
3
metadata: {
4
type: 'json',
5
},
6
};
7
8
console.log(myObject?.metadata?.type);
In dirask snippets you can find some reusable arrow functions:
2. Alternative solution
You can create a custom function:
xxxxxxxxxx
1
function getValue(object, path) {
2
return path.reduce(function (value, key) {
3
return value == null ? value : value[key];
4
}, object);
5
}
6
7
8
// Usage example:
9
10
var myObject = {
11
name: 'John',
12
metadata: {
13
type: 'json',
14
},
15
};
16
17
var metadata = getValue(myObject, ['metadata', 'type']);
18
19
console.log(metadata); // json
See also
References
0 commentsShow commentsAdd comment