chemook78
chemook78

Reputation: 1198

Check for objects with certain key/value pair in switch statement Javascript

I have an array with numbers and objects, for example:

var array = [0,0,1,0,2, {type:player, health:100, xp: 0}, 0,2,1,0, {type:weapon, damage:20}]

Then I loop through the array and set a string in a variable that I use to dynamically set classes.

For now I have the following loop with switch statement:

for(var i = 0; i < array.length; i++){

        var setClass = "";

        switch (array[i]) {

          case 1:
            setClass = "walkable";
            break;
          case 2:
            setClass = "wall";
            break;
          default:
            setClass = "outside"

        }
}

What I want to do is in the switch statement check if the item in the loop is 1) an object and 2) with a certain key/value pair?. So I would like to set the string to something for type:player and something else for type:weapon. How can I do that?

Upvotes: 0

Views: 3176

Answers (3)

JWS
JWS

Reputation: 168

You could use within the loop

array.forEach(function(element) {
    if (element.hasOwnProperty('type')) {
          switch (element.type) {
              case "player":
                ...
                break;
              case "weapon":
                ...
                break;
              default:
                ...
            }
    }
});

Upvotes: 0

Supradeep
Supradeep

Reputation: 3266

Hope this is what you are trying to accomplish :

 for(var i = 0; i < array.length; i++){

    var setClass = "";
    if(array[i] !== null && typeof(array[i]) === "object"){

      switch (array[i]) {

      case "player":
        setClass = "walkable";
        break;
      case "weapon":
        setClass = "wall";
        break;
      default:
        setClass = "outside"

     }
    }
}

Upvotes: 0

Akhil Arjun
Akhil Arjun

Reputation: 1127

I hope this is what you are expecting.

var array = [0,0,1,0,2, {type:player, health:100, xp: 0}, 0,2,1,0, {type:weapon, damage:20}]

for(var i = 0; i < array.length; i++){

        var setClass = "";

        switch (array[i]) {

          case 1:
            setClass = "walkable";
            break;
          case 2:
            setClass = "wall";
            break;
          default:
            if (Object.prototype.toString.call(array[i]) === '[object Object]'){
                //This means the value is an Object
                //And here you can check its type like
                if (array[i].type === 'player') {
                    //Do something
                }
            }
            setClass = "outside"

        }
}

Upvotes: 1

Related Questions