Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading