Home > other >  How to null check object property with a variable
How to null check object property with a variable

Time:06-23

data, roles and infos are variables that came from an API, Here I manually add array's index whereas in my code I loop the keys.

How to one line check if the attribute is null ?

Is there a way to access property like x?[roles[0]]?[infos[0]]

const data = [{player: {fname: 'player', lname: 'one'}, 
              { enemy: {lname: 'two'},
              {  ally: {fname: 'player'}]
const roles = ['player','ally']
const infos  = ['fname','lname']

data.map(x => {
    const firstPlayer  = `${x[roles[0]][infos[0]]} ${x[roles[0]][infos[1]]}`
    const secondPlayer = `${x[roles[1]][infos[0]]} ${x[roles[1]][infos[1]]}`
    return `hello ${firstPlayer} and ${secondPlayer}`
});

CodePudding user response:

You can use optional chaining, this works on array indexes also.

const firstPlayer  = `${x?.[roles[0]]?.[infos[0]]} ${x?.[roles[0]]?.[infos[1]]}`

Just note that you'll get undefined inside the string if the chain is broken.

CodePudding user response:

I would use a fallback value to cover undefined values like this:

const data = [
{
      player: {
        fname: 'player',
        lname: 'one'
      },
      
        enemy: {
          lname: 'two'
        },
        
          ally: {
            fname: 'player'
          }}];
        const roles = ['player', 'ally'];
        const infos = ['fname', 'lname'];

        const res = data.map((x) => {
          const firstPlayer = (x[roles[0]][infos[0]] || '')   ' '   (x[roles[0]][infos[1]] || '')
          const secondPlayer = (x[roles[1]][infos[0]] || '')   ' '   (x[roles[1]][infos[1]] || '')
          return ('hello '   firstPlayer   ' and '   secondPlayer).trim();
        });

        console.log(res);

P.s. Sorry if i changed from ` strings to ' strings concat, but this snippent doesn't allow ` syntax.

  • Related