0

Using pure javascript -- no third party / lodash etc.

Given a user looking for the existence of a deep nested node, is there a cleaner way to ensure each parent node exists so as to not return undefined?

Keeping it simple, check that a nested prop has length before performing an action.

The problem is, especially when passing props, at any given node, you could end up with undefined.

Is there a way to avoid checking that each node exists like this:

if( !!Grandparent && !!Grandparent.Parent && !!Grandparent.Parent.child && !!Grandparent.Parent.child.prop3.length){
    // do something
}

Something more like this: (which I know is not correct as any node being undefined hoses the process).

if(!!Grandparent.Parent.child.prop3.length) {
    // do something
}

// OR

if(typeof Grandparent.Parent.child.prop3.length !== "undefined"){
    // do something
}

EX:

   Grandparent: {
        Parent: {
            child: {
                prop1: 'alpha',
                prop2: 'beta',
                prop3: [
                    item: {
                        name: 'first',
                        type: 'string'
                    },
                    item: {
                        name: 'second',
                        type: 'number'
                    }
                ]
            }
        }
    }
Acts7Seven
  • 417
  • 1
  • 6
  • 14
  • 2
    Use [null-safe optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)? There are also various implementations of `get`- and `dig`-like methods, but `?.` is cleaner (IMO). – Dave Newton Sep 22 '21 at 16:10
  • Use optional chaining operator. `if (foo?.bar?.zoo?.etc) {…}` – hackape Sep 22 '21 at 16:10
  • However if `foo` is undefined , you still get undefined. Here's a codedsandbox: https://codesandbox.io/s/sweet-hellman-b4z9f?file=/src/index.js – Acts7Seven Sep 22 '21 at 16:15

1 Answers1

1

As commenters have indicated, modern JavaScript provides the optional chaining operator (?.), which you can use like this (as long as you're not still trying to support IE):

const
  grandparent = getObject(),
  itemsCount = grandparent?.parent?.child?.prop3?.length,
  oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");


function getObject(){
  return {
    parent: {
      child: {
        prop1: 'alpha',
        prop2: 'beta',
        prop3: [
          { item: { name: 'first', type: 'string' }},
          { item: { name: 'second', type: 'number' }}
        ]
      }
    }
  };
}
Cat
  • 4,141
  • 2
  • 10
  • 18
  • I've encountered an issue in that if any of these are undefined I will get an error. Even if checking the null-safe operator for typeof object !== undefined. Here's my codesandbox what am I doing wrong? https://codesandbox.io/s/sweet-hellman-b4z9f?file=/src/index.js – Acts7Seven Sep 22 '21 at 16:29
  • The problem was that in your sandbox, the variable `props` was not just undefined but totally **undeclared**. The compiler didn't know what to do about that and threw the problem back to you with an error. – Cat Sep 22 '21 at 16:45
  • Thank you!!!! I just came to the same conclusion -- Sometimes its the little things that get me. Appreciate your help. – Acts7Seven Sep 22 '21 at 16:48