glaemart
glaemart

Reputation: 127

For Loop To Get One Variable From Each Nested Array

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

Upvotes: 0

Views: 63

Answers (1)

yBrodsky
yBrodsky

Reputation: 5041

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

Upvotes: 1

Related Questions