0

How would I access the value of statusCode for example?

{
    res: IncomingMessage {
      statusCode: 200,
      statusMessage: '',
    }
}
Liam
  • 25,247
  • 27
  • 110
  • 174
newprogrammer
  • 530
  • 6
  • 17

4 Answers4

1

It depends on the initial object.

If outer brackets is valid then you can access it like property name:

object.res.statusCode

or you can do it by propertyName:

object['res']['statusCode']

If outer brackets is not valid and you wrote them just for wrapping up. Then you can access status code the same way, just without mentioning res.

0

Optional Chaining.

Not widely supported in older browsers:

data?.res?.statusCode

Using dot notation:

data.res && data.res.statusCode;

Using property access notation:

data['res'] && data['res']['statusCode']

Using ternary operator:

data['res'] ? data["res"]["statusCode"] : -1
someone
  • 358
  • 1
  • 14
khizer
  • 928
  • 9
  • 11
-1

JSONObject.res.statusCode is a correct approach.

In case that you have something like this (Replace JSONObject with the name of your JSON) :

 let JSONObject = {
        res: IncomingMessage {
          statusCode: 200,
          statusMessage: ''
        }
    }
Ognjen
  • 134
  • 8
  • You can't have a JSON Object... JSON is a string notation – Liam Jul 02 '20 at 14:05
  • 1
    Yes...That is what JSON means... It's still not an object. **Notation** as in text – Liam Jul 02 '20 at 14:06
  • [JavaScript Object Notation (JSON) is a standard **TEXT-BASED** format for representing structured data **BASED ON** JavaScript object syntax](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON) – Liam Jul 02 '20 at 14:08
-1

Your Object structure is wrong maybe you meant this

ob={ res:{ IncomingMessage :{ statusCode: 200,statusMessage: ''}}}
console.log(ob.res.IncomingMessage.statusCode)
Sven.hig
  • 4,411
  • 2
  • 6
  • 18
  • 2
    why is the downvote!! can anyone explain to me what is wrong with the answer, I am all open to criticism. However downvoting without explaining why, makes no sense – Sven.hig Jul 02 '20 at 14:11