0

I would like to understand what I did wrongly. I have tried to read this, but it was overwhelmingly detailed: Access / process (nested) objects, arrays or JSON

{
    "dogs":[
         {
             "name": "shiba",
             ....
         }
         {
             "name": "akita",
             ....
         }
      ]
 }

I read the JSON from an HTTP server and it was returned as data.

       for(var item in data["dogs"])
       {
         console.log(item["name"]);
         console.log(data["dogs"][0]["name"]);
       }

console.log(item["name"]); does not work, returning 'undefined'. console.log(data["dogs"][0]["name"]); works, but since it has a fixed index, it does not iterate all names. Why isn't the first one working?

In VS Code, if I set a breakpoint at that line, somehow the breakpoint does not stay. It gets hit but continues away in a second, so I cannot examine the data. Before running, if I place the mouse on item, the popup says that the type is string. Why is it a string; shouldn't it be 'any'?

Damn Vegetables
  • 11,484
  • 13
  • 80
  • 135
  • 3
    JS's `for...in` doesn't do what it looks like it should do. It iterates the keys of an object, not the elements of an array. If you use `for (let item of data["dogs"])` (note `of` instead of `in`) it should work, as long as you're targeting ES6 or above. (Below ES6, you'll have to use a helper function such as `$.each`.) – Benjamin Hodgson Dec 06 '17 at 02:15
  • Thank you. I changed 'in' to 'of', and it worked as I intended. So, 'in' is for keys, 'of' is for values. – Damn Vegetables Dec 06 '17 at 02:20

0 Answers0