-1

Coding in javascript, and I am trying to put objects into arrays, and the Array looks like

arr = [
{"id":1,"location":"Place1"},
{"id":2,"location":"Place2"}
]

I am trying to do arr[1].location, but arr[1] is undefined and console.log(arr[0]) and arr[1] in inspect element just returns as a "{". Im not sure if this is a chrome thing, but node does seem to accept the format.

Edit: I am collecting from a api that I made and this is the format it returns the code, I am just trying to access variable location. I am asking how would I get said variable

Problem answered in comments, didn't parse data.

Tony Baloney
  • 31
  • 1
  • 6
  • Where and how are you defining `arr` (it's not in your question)? When and where are you then trying to access `arr[0]`, `arr[1]`, etc? _"Inspect element"_ is for DOM (HTML) elements so I'm not sure what that has to do with your question at all – Phil Apr 01 '20 at 02:27
  • Your code should work fine, try assigning the variable `arr` like so: `let arr = [ { "id": 1, "location": "Place1" }, { "id": 2, "location": "Place2" } ]; console.log(arr[1].location);` – Luís Ramalho Apr 01 '20 at 02:37
  • Could you please address **all** the questions in the first comment above? Given now you mention an API, I suspect this will answer your question but will wait to see what you think ~ [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Apr 01 '20 at 02:53
  • I made the array into a variable now so It is not confusing. I noticed theres no arr in code so I also fixed it. And yes metaphorical "arr" is defined but "arr[0]" is not – Tony Baloney Apr 01 '20 at 02:55

2 Answers2

1

Did you try parsing your data when received :

JSON.parse(apiResponse)
jcoleau
  • 1,112
  • 7
  • 20
-1

The problem was the way I handled the data. Instead of using a XMLHttpRequest for the array, I used jquery to request the data, and that seemed to work better for my API.

Tony Baloney
  • 31
  • 1
  • 6