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

asked Feb 19, 2018 at 16:10
6
  • stackoverflow.com/questions/500504/… Commented Feb 19, 2018 at 16:12
  • 1
    const cityList = data.State.map(element => element.city_name); Commented Feb 19, 2018 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. Commented Feb 19, 2018 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. Commented Feb 19, 2018 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" Commented Feb 19, 2018 at 16:35

1 Answer 1

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

answered Feb 19, 2018 at 16:36
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.