0

I am trying to go through some Json and just get the "city_name" value from each nested array and print it in a list. QUESTION: How do you loop over an array and just get the first element from each array?

“state”: [
    {
      “city_name”: “Denver”,
      “timezone”: “MST”,
    },
    {
      “city_name”: “Austin”,
      “timezone”: “CST”,
    }
{
      “city_name”: “Atlanta”,
      “timezone”: “EST”,
    }
  ],

Javascript that I tried:

fetch(‘URL’).then(function(response) { 
        return response.json();
    }).then(function(data) {
        console.log(data);
        for (x in data.state) {
        document.getElementById("cities").innerHTML += data.state.city_name + "<br>";
    }    
    });

Response: undefined undefined undefined

Is this the correct way to get the value inside the array? Why does it say undefined? *this is just sample data to help explain my problem

glaemart
  • 129
  • 1
  • 10
  • https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea – str Feb 19 '18 at 16:12
  • 1
    `const cityList = data.State.map(element => element.city_name);` – Pavlo Feb 19 '18 at 16:14
  • Because you don't have a property named `"state"`. It's `"State"` and it's an array so you should use `for ... of` instead of `for ... in`. – Derek 朕會功夫 Feb 19 '18 at 16:19
  • Pavlo: I tried the const cityList = data.State.map(element => element.city_name); But this just repeated Denver 3 times. I placed it inside the For Loop and outside. – glaemart Feb 19 '18 at 16:32
  • Derek: The capital State was a typo in my sample, I've corrected it. I tried changing it to For "of" but that still resulted in "undefined" – glaemart Feb 19 '18 at 16:35
  • It says undefined because the property `state` is an array, and the array itself doesn't have a property called `city_name` (so, `data.state.city_name` is wrong). You have to iterate the array and retrieve each element which *does* have a property called city_name (so, `data.state[x].city_name` depending on how you iterate it, don't use for..in). The answer and comment that use `map` are both appropriate and both would work. If they don't work then your data is not what you have posted above. – James Feb 19 '18 at 16:44

1 Answers1

1
fetch(‘URL’).then(function(response) { 
  return response.json();
}).then(function(data) {
  let cities = data.state.map(e => e.city_name);
  document.getElementById("cities").innerHTML += cities.join('<br/>');
});

This should work assuming data is an object containing a property state

yBrodsky
  • 4,981
  • 3
  • 20
  • 31