Searching for specific key/value pairs in a switch statement in JavaScript

I am working with an array that contains both numbers and objects. Here is an example:

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

To dynamically set classes, I loop through the array and store a string in a variable.

Currently, my loop includes a switch statement like this:

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"

        }
}

Now, I want to enhance this switch statement by checking if the item in the loop is 1) an object and 2) has a specific key/value pair. Specifically, I would like to assign different strings based on the type of the object - whether it's a player or a weapon. How can I achieve this?

Answer №1

I trust this meets your expectations.

let list = [0, 3, 1, 0, 4, {category:player, health:100, experience: 0}, 0, 4, 2, 1, {category:gear, power:20}]

for(let j = 0; j < list.length; j++){

        let defineClass = "";

        switch (list[j]) {

          case 1:
            defineClass = "passable";
            break;
          case 2:
            defineClass = "barrier";
            break;
          default:
            if (Object.prototype.toString.call(list[j]) === '[object Object]'){
                //This indicates the value is an Object
                //You can also verify its category like
                if (list[j].category === 'player') {
                    //Perform some action
                }
            }
            defineClass = "outer"

        }
}

Answer №2

Here is a possible solution to achieve your goal:


for(let index = 0; index < arr.length; index++){
    let customClass = "";
    
    if(arr[index] !== null && typeof(arr[index]) === "object"){
        
        switch (arr[index]) {
            case "player":
                customClass = "walkable";
                break;
            case "weapon":
                customClass = "wall";
                break;
            default:
                customClass = "outside"
         }
     }
}

Answer №3

To iterate through the array, you can utilize a loop

array.forEach(function(item) {
    if (item.hasOwnProperty('category')) {
          switch (item.category) {
              case "laptop":
                ...
                break;
              case "phone":
                ...
                break;
              default:
                ...
            }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Watching for changes in a callback function - Angular 2

I'm currently working on implementing a callback function within a service class that needs to send data back to the component class. ChatComponent.ts export class ChatComponent implements OnInit { constructor( public _chatService : ChatService) ...

Using Vue's v-if statement to determine if a variable is either empty or null

Using a v-if statement to display certain HTML only if the archiveNote variable is not empty or null. <div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div"> Here is how it's implemented ...

Securing page access with a straightforward password protection using Flask

Looking for a straightforward way to add password protection to a Flask app site. I've explored options like flask_login, but they seem overly complex for my needs. I don't need high security or login sessions - just something like: "enter passw ...

Problem with Button Functionality in Outlook Email

I am having trouble making a specific button for Outlook within my email. Due to the different sections in my EMAIL, the button got wrapped in v:rect and now it is shifting to the top of the email. Can someone assist me with this issue? Actual Image - htt ...

The Angular FormGroup may not reflect the updated value right away after using patchValue or setValue methods

Below is a form I have created: createForm() { this.procedimentoForm = this.formBuilder.group({ nome: ['', Validators.required], descricao: ['', Validators.required], conteudo: ['', Validators.required] ...

Ways to utilize jQuery for intricate forms in place of RJS

Within the 74th episode of Railscasts, Ryan demonstrates the process of executing intricate forms with RJS. Check it out here: The key here is to generate a partial and incorporate it using RJS. This episode is quite dated and back then, jQuery may not ha ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

Tips for avoiding jquery ajax events from throwing errors upon loading a new page in Firefox

I am facing a peculiar issue with jQuery $.ajax events in Firefox 8 and above. When a new page is loaded while these events are waiting for a response from the server, they all throw errors. Surprisingly, JavaScript on the current page continues to run eve ...

Is there potential for chaos when forward declaring an array of pointers to structs?

Within my code, I have a struct called S and an array of pointers to S structs called A. The function T is designed to take a pointer to struct S as an argument. struct S *A; // declaring array A to hold pointers to structs ... void T(struct S *s){// fun ...

Tips for optimizing search functionality in Angular to prevent loading all data at once

An exploration for information within vast datasets is triggered by AngularJS when the input contains more than 3 characters. var app = angular.module('test_table', []); app.controller('main_control',function($scope, $http){ $scope ...

Creating curved triangles in React Native is a fun and easy way to add stylish

Hello everyone, I am a newcomer to react native and I am attempting to create the following user interface. Is there any way to create a curved triangle? I have tried but I am unable to curve the edges of the triangle. https://i.stack.imgur.com/vE17U.png ...

Exploring the loading of stateful data in ReactJS and implementing optimizations

Exploring the world of ReactJS in conjunction with Django Rest Framework (DRF) def MyModel(model): ... status = ChoiceField(['new', 'in progress', 'completed'...]) In my application, I have dedicated sections for eac ...

Methods for displaying a placeholder in a semantic-ui-vue dropdown without using the multiple attribute

When utilizing the dropdown feature in semantic-ui-vue, I have encountered an issue where the placeholder option does not function unless the multiple attribute is included. You can view my sandbox demonstration at this link. I have set up 2 dropdowns: ...

What strategies should be employed to manage data-driven input in this particular scenario?

In the process of creating a small webpage, I have designed 2 navigation panels - one on the left and one on the right. The leftNav panel contains a list of different flower names. While the rightNav panel displays images corresponding to each flower. A ...

Using Web SQL always seems to throw me for a loop

I attempted to populate a web SQL database with some data, but encountered an issue. Here is my code: database(); for(var i=0; i<m.length; i++){ showid = m[i].id; showtitle = m[i].title; insert(); } function database(){ //open the database ...

Bug in Firefox 12 affecting the invocation of Applet Methods

My issue arises specifically with Firefox 12 (newer versions of Firefox and other browsers function correctly). In Firefox 12, MyApplet is showing as undefined. However, in other browsers, everything is running smoothly. The same goes for newer versions ...

Ways to determine the presence of a value in an array using AngularJs

I'm currently working on looping through an array to verify the existence of email, phone, and alternate phone in a database. My challenge lies in finding a suitable function or workaround in AngularJS that allows me to iterate through the array with ...

Using VueJS to Create a Range of Years from 1900 to Present Year

I'm currently developing a registration form using VueJS, wherein users need to input their date of birth. My challenge is in generating a list of years starting from 1900 up to the current year within a <select> element. Any suggestions on how ...

What is the best way to upload items by utilizing text input and a submission button?

I've been experimenting with loading obj files using three.js and webGL. Currently, I can load one object by directly modifying the code, but now I want to give users the ability to upload their own .obj files. Here is the code snippet that I have so ...