Noob Question: How do I access this value in JavaScript?

72 Views Asked by At

I've never used JavaScript before and I'm stumped about how to access a particular value in an Object.

The JSON looks like this:

{
   "payload":{
      "params":{
         "switch:0":{
            "output":false,  **<= trying to get this value ("false")**
         }
      }
   },
}

Node-Red, the tool I'm working with, represents the object like this in its debug pane:

Node-Red Object Debug

I assumed this was an array and could be accessed like so:

    value = msg.payload.params.switch[0].output

But I get an error:

"TypeError: Cannot read property '0' of undefined"

If I try:

  value = msg.payload.params.switch

the value is reported as "undefined".

What is the correct way in JavaScript to access the value of "output"? I googled a bunch trying to find an answer, but have been unsuccessful.

Any help is appreciated!

1

There are 1 best solutions below

0
On BEST ANSWER

Use bracket notation to access the "switch:0" property since it is not a valid identifier.

let o = {
   "payload":{
      "params":{
         "switch:0":{
            "output":false, 
         }
      }
   },
}
let res = o.payload.params['switch:0'].output;
console.log(res);