skip to Main Content

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


  1. You can try undefined check using optional chaining (?.) and nullish coalescing (??) operators like the following way:

    const data =  {
        body: {
          data: {
            names: [
              {
                firstName: 'John'
              },
              {
                firstName: 'Johnn'
              }
            ]
          }
        }
      };
    
    //test
    const firstName = data?.body?.data?.names?.[0]?.firstName ?? 'Unknown';
    
    console.log(firstName);//'John'
    
    //test: undefined
    const dataWithoutNames = {
      body: {
        data: {}
      }
    };
    
    const unknownName = dataWithoutNames?.body?.data?.names?.[0]?.firstName ?? 'Unknown';
    
    console.log(unknownName);//'Unknown'
    Login or Signup to reply.
  2. 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:

    const _ = require('lodash');
    ...
    const firstName = _.get(yourData, 'body.data.names[0].firstName');
    

    The get function enables easy access to nested properties without the need to worry about undefined values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search