1

So I have the http.get call working and can correctly grab data from the request:

this.http.get('https://data.cityofnewyork.us/resource/xx67-kt59.json').subscribe(data => {
      // Read the result field from the JSON response.
      console.log(data);

  for (let x in data) {
    console.log(x);
  }
});

The console.log(data) line works successfully, it prints me out an array of th e items from the request.

The trouble I'm having is when I try and iterate through each individually item in the JSON array.

for (let x in data) {
   console.log(x);
}

Just prints me out the index/number of the item in the JSON object. Even if I try x["prop name"], it still fails.

Even the following doesn't work:

console.log(JSON.stringify(x));

My goal is to eventually map these to a class I'd define and populate an array variable with that data.

Am I being stupid in how I'd reference the JSON property for each item?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Zeratas
  • 1,005
  • 3
  • 17
  • 36
  • 1
    Does this help? https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-in-javascript – Alex Szabo Jan 05 '18 at 19:44

2 Answers2

2

If you want to iterate over an Array you should use the for of construct.

for (let x of data) { 
  // `x` is an item from the array
} 

The for in construct iterates over the keys of an object. In your case those are the array indexes.

Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
  • Wow, did not know that, thanks! I tried it but now it's giving me an error saying "Type OBJECT is not an array type or a String type". Does this mean I have to JSON.stringify it? I thought Angular returned JSON in it's HTTP calls. I had just tried it and it seems like it's not printing out every.single.character individually. – Zeratas Jan 05 '18 at 20:06
  • If you are using `import { HttpClient } from '@angular/common/http'`, you don't have to parse the response body to JSON. Can you please post more of your code? – Tsvetan Ganev Jan 05 '18 at 20:56
  • I was able to figure it out. There was also something screwy with my TSlint file so it kept giving me an error when there was none. Thanks! – Zeratas Jan 16 '18 at 15:59
0

Try using for (let x of data) instead of for (let x in data).

MisterMystery
  • 402
  • 6
  • 14