Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js/Javascript, how to check if value exists in multidimensional array?

Lets say I have array something like this:

$game = Array
(
    ['round'] => Array
        (
            ['match'] => Array
                (
                    ['player_2'] => Array
                        (
                            [name] => asddd
                            [id] => 1846845
                            [winner] => yes
                        )

                    ['player_21'] => Array
                        (
                            [name] => ddd
                            [id] => 1848280
                            [winner] => no
                        )

                )
        )
)

And lets say in Node.js/Javascript I need to check if player_3 winner key value is yes. In PHP, you did something like this:

if( $game['round']['match'][player_3]['winner'] == 'yes'){

}

Because there is no player_3 it returns false in PHP, but if I did something similar in Javascript:

 if( typeof game['round']['match'][player_3]['winner'] != 'undefined' && game['round']['match'][player_3]['winner'] == 'yes'){

 }

I would get error: (node:15048) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined, because player_3 doesn't exist in array and you can't check key value of array, that doesn't exist.

You could do this in Javascript:

if( 
   typeof game['round'] != 'undefined' &&
   typeof game['round']['match'] != 'undefined' &&
   typeof game['round']['match']['player_3'] != 'undefined' &&
   typeof game['round']['match']['player_3']['winner'] != 'undefined' &&
   typeof game['round']['match']['player_3']['winner'] == 'yes'
){
   var playerIsWinner = true;
}else{
   var playerIsWinner = false;
}

You check each array inside array from top down and make sure that they exists. I don't know if it actually works, but even if it does, it seems bad and stupid way to check something. I mean look how simple it is in PHP, while in Javascript I have to check each array existence inside array. So is there better way checking value of array?

like image 425
user1203497 Avatar asked Oct 18 '25 13:10

user1203497


1 Answers

Please, look at the lodash library, especially at methods, such as get. Then you may safely try something like:

_.get(game, 'round.match.player3.winner', false);

That's it :)

like image 190
Artem Avatar answered Oct 21 '25 03:10

Artem