0

I am doing following in my javascript code

if(
  typeof player['stats'] != undefined &&
  typeof player['stats']['guild'] != undefined &&
  typeof player['stats']['guild']['master'] != undefined &&
  typeof player['stats']['guild']['master']['since'] != undefined
)

However I get error:

Cannot read property 'since' of null

I have been stuck with this for a while. Can any javascript gurus help me please?

Undefined Variable
  • 4,196
  • 10
  • 40
  • 69

4 Answers4

1

typeof returns string, so compare against "undefined"

if(
  typeof player['stats'] != "undefined" &&
  typeof player['stats']['guild'] != "undefined" &&
  typeof player['stats']['guild']['master'] != "undefined" &&
  player['stats']['guild']['master'] != null &&
  typeof player['stats']['guild']['master']['since'] != "undefined"
)
Dij
  • 9,761
  • 4
  • 18
  • 35
1

Just check if the value is truthy:

if(
  player['stats'] &&
  player['stats']['guild'] &&
  player['stats']['guild']['master'] &&
  player['stats']['guild']['master']['since'] != undefined    // only check the last one as it is probably not an object but another value such as 0 (depending on what your data looks like, if you have it as an object then just remove the != undefined check)
)
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

You could write a fairly simple object getter function which you pass the object and then a dot-delimited key to find a value like so:

function getObj(obj, key) {
  return key.split(".").reduce((acc, cur) => {
    if (acc !== undefined) {
      return acc[cur];
    }
    return acc;
  }, obj);
}

Then, you can grab the value that you want and see if it's undefined or not:

const player = {
  stats: {
    guild: {
      master: {
        since: '2004'
      }
    }
  }
};

const since = getObj(player, 'stats.guild.master.since');
if (since) {
  // do some code
}

This is a handy utility function you can use on any object and makes your if statement much prettier.

jas7457
  • 1,712
  • 13
  • 21
  • I think this will work only if you remove the ` !== undefined` and add it in the if statement `if (since !== undefined)` because in his case master is `null` – Slai Sep 17 '17 at 00:03
  • Updated so it gracefully handles null and undefined: https://jsfiddle.net/vhnoqo8u/ – jas7457 Sep 17 '17 at 00:11
0

You can also avoid the multiple lookups with a temporary variable:

player = { stats: { guild: { master: null } } }

if ((temp = player.stats) && 
    (temp = temp.guild)   && 
    (temp = temp.master)  && 
    (temp = temp.since) !== undefined)        
    console.log(true , temp)
else
    console.log(false, temp)


player.stats.guild.master = { since: 'today' }

if ((temp = player.stats) && 
    (temp = temp.guild)   && 
    (temp = temp.master)  && 
    (temp = temp.since) !== undefined)        
    console.log(true , temp)
else
    console.log(false, temp)
Slai
  • 22,144
  • 5
  • 45
  • 53