简体   繁体   中英

Why am I getting [object Object] after accessing JSON data?

I am making a simple GET request and filling up a webpage with some data. Every other line works except for 'addresses' which contains two arrays, and on my webpage it prints out '[object Object]', instead of the data. Here is an example of the JSON (apologies for the poor formatting):

data: Array(7)
   0:
   addresses: Array(2)
   0:
     city: "Houghton"
     line1: "800 East Lakeshore Drive"
     line2: ""
     line3: ""
     postalCode: "49931"
     stateCode: "MI"
     type: "Physical"

proto : Object

Here is the code block where I try to access 'addresses':

for (let i = 0; i < parkData.length; i++) {
    $("#results-list").append(`<h2>${parkData[i].fullName}</h2>
    <p>${parkData[i].addresses[0]}</p>
    <a href=${parkData[i].directionsUrl}>Directions</a><br>
    <a href=${parkData[i].url}>Website</a>
    <p>${parkData[i].description}</p>

Like I said above, all of the other lines work but when I try to get the first index of addresses I just get that weird Object response. Any ideas? Thank you!

[object Object] means that it's not a string but an object that (probably) has an address as property of this object, ie instead of parkData[i].addresses[0] you need to access some property (which one I cannot tell from your code as you are not showing the whole object that you got from JSON), for example like this:

const {city, line1} = parkData[i].addresses[0].city
const fullAddress = `City: {city}, Address: {line1}`

And only then, after constructing the address, you add it into your page as fullAddress

This is because you need to go deeper in some of the properties for sure. Double check every iteration and you will find that you are appending an object. I think you didn't paste all the response. You can use jsonviewer to better see the structure

Edit-> As I can see...address is an object, so you need to iterate over it in order to append strings.

So it would be: ... address[0].map(a => ... a.someAddressProperty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM