0

I have this code

request(options, (error, response) => {
  const data = JSON.parse(response.body)
  //console.log( JSON.stringify(data, null, " ") );
  console.log(data);
})

Which gives me this output

{
 result: 'OK',
 data: {
   body: {
     pdpHeader: [Object],
     overview: [Object],
     hotelWelcomeRewards: [Object],
     propertyDescription: [Object],
     guestReviews: [Object],
     atAGlance: [Object],
     hotelBadge: [Object],
     unavailable: {}
  },
  common: { pointOfSale: [Object], tracking: [Object] }
  },
  transportation: { transportLocations: [ [Object], [Object], [Object] ] },
  neighborhood: { neighborhoodName: 'Manhattan' }
}

Within the actual body of this output there is this:

{4 items
"result":"OK"
"data":{2 items
    "body":{14 items
        "pdpHeader":{6 items
            "hotelId":"424023"
            "destinationId":"1506246"
            "pointOfSaleId":"HCOM_US"

I want to call out the hotelID number: 424023

I have tried the following a few other modifications to this, but cannot seem to call out the correct object

console.log(data.body.pdpHeader.hotelID)

But I get the error message

console.log(data.body.pdpHeader.hotelID);
                    ^

TypeError: Cannot read property 'pdpHeader' of undefined
2
  • 2
    I think you want data.data.body .... etc ... I assume the variable holding this object is called data ... if it were called graham you'd use graham.data.body ... does that make sense now? can you see where you went wrong? Commented Jul 26, 2021 at 11:02
  • 1
    it's not hotelID it's hotelId Commented Jul 26, 2021 at 11:06

1 Answer 1

4

You've called your const data as well, so you'll either need to destruct or call .data again, like so.

Destruct

You can destruct the propery onto your data const like so:

const { data } = JSON.parse(response.body)
// data.body.pdpHeader.hotelID

Assignment

If you don't want to destruct, call data.data as per below.

const data = JSON.parse(response.body)
// data.data.body.pdpHeader.hotelID
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.