Sachin Naik
Sachin Naik

Reputation: 355

accessing an object inside array in javascript

Here is an example of state machine I intend to build

  this.statemachine =
      {
           state: 'idle',
           transitions:
           {
                  idle:{
                          ebaseinit: function ()
                          {
                             console.log("Firebase Init complete");
                          } ,

                          coreinit : function ()
                          {
                             console.log("Firestore Init complete");
                          }

                       },
                   ready:
                      {
                         fetchdata : function ()
                         {
                           console.log("Getting                                   data");
                         }
                         

                      }    
           }
      }        
Depending on the event that occurs I need to invoke respective function. Tried this.statemachine.transitions.indexof("idle") It does not work. Any suggestion to implement accessing the function without using direct numbers like this.statemachine.transitions[1] etc should help

Upvotes: 1

Views: 68

Answers (2)

Nijeesh K J
Nijeesh K J

Reputation: 59

First thing you have to understand is statemachine.transitions is not an array it is an object thats why you cant use indexOf on it

if(this.statemachine.transitions)
 let obj = this.statemachine.transitions[statemachine.state]

or

You can use a for loop to iterate through the object and find what you are looking for

if (this.statemachine.transitions){
      for (var key in this.statemachine.transitions) {
        if (this.statemachine.transitions.hasOwnProperty(key)) {
          if(this.statemachine.state == key){
            console.log(this.statemachine.transitions[key])
          }
        }
      }
    }

Upvotes: 1

Cristian S.
Cristian S.

Reputation: 973

You can catch the event name and use it as an object key.

this.statemachine.transitions['ready']

Upvotes: 1

Related Questions