I’d like to simplify JSON object check for undefined values:
{
body: {
data: {
names: [
{
firstName: 'John'
},
{
firstName: 'Johnn'
}
]
}
}
}
So if I do it like this then it throws an exception if names is an empty array []:
body?.data?.names[0]?.firstName
So should I go old way like this?
if (
body &&
body.data &&
body.data.names &&
body.data.names.length > 0 &&
body.data.names[0] &&
body.data.names[0].firstName
) {
// ....
}
2
Answers
You can try
undefined
check usingoptional chaining (?.)
andnullish coalescing (??)
operators like the following way:Another option, in case you need to work with complicated JSON objects, is using the Lodash JavaScript library. It offers useful functions for everyday programming tasks, all using the functional programming approach. After installing it by
npm install lodash
:The
get
function enables easy access to nested properties without the need to worry about undefined values.