最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to loop through JSON object together with an if-statement? - Stack Overflow

matteradmin6PV0评论

This is the JSON object:

{
    "temperatures": {
        "city": [{
            "name": "Riyadh",
            "high": [35, 38, 32]
        }, {
            "name": "New York",
            "high": [28, 36]
        }, {
            "name": "Dubai",
            "high": [18, 20]
        }]
    }
}

On page load I get the object via AJAX. I need to loop through each city and get the name of the city and the high array as well.

This is the page code:

<html>

    <head>
        <title>the title</title>

        <script type="text/javascript" src="tempj.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {

            $.getJSON('temp.json', function(data) {
                alert('<ul><li>'+ jd.city.name +':'  + jd.high + '</ul> ');
            });
        });
        </script>

    </head>

    <body>
    </body>

</html>

This is the JSON object:

{
    "temperatures": {
        "city": [{
            "name": "Riyadh",
            "high": [35, 38, 32]
        }, {
            "name": "New York",
            "high": [28, 36]
        }, {
            "name": "Dubai",
            "high": [18, 20]
        }]
    }
}

On page load I get the object via AJAX. I need to loop through each city and get the name of the city and the high array as well.

This is the page code:

<html>

    <head>
        <title>the title</title>

        <script type="text/javascript" src="tempj.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {

            $.getJSON('temp.json', function(data) {
                alert('<ul><li>'+ jd.city.name +':'  + jd.high + '</ul> ');
            });
        });
        </script>

    </head>

    <body>
    </body>

</html>
Share Improve this question edited Nov 4, 2011 at 5:40 Samuel Liew 79.2k111 gold badges169 silver badges304 bronze badges asked Nov 4, 2011 at 5:29 proRproR 392 silver badges9 bronze badges 1
  • 1 stackoverflow./questions/1078118/… and stackoverflow./questions/2342371/… might help u – run Commented Nov 4, 2011 at 5:48
Add a ment  | 

3 Answers 3

Reset to default 3

I don't know what you mean in your question title about using an if statement, so I'm ignoring that.

Within your JSON, data.temperatures.city is an array of objects each of which has two properties, one for the city name and one an array of highs. I have no idea how you want to handle the fact that the highs arrays have different lengths, so I've just used the .join() method to form them into a ma-separated string on the end of the message in the alert.

Presumably you don't really want to pop up a bunch of alerts, but at least that's a starting place to see that you're getting the data you expect so the following should be enough to get you going:

$.getJSON('temp.json', function(data) {
   for (var i = 0; i < data.temperatures.city.length; i++) {
      alert("The temperatures in " + data.temperatures.city[i].name + " are "
            + data.temperatures.city[i].high.join(","));
   }
});

I deliberately didn't use $.each() so that for learning purposes you can see what's going on. Obviously you can convert this to use $.each() if you prefer.

You should add error checking that the properties you are trying to use actually exist (i.e., that the JSON is in the expected format).

You can reach into the data to get to the city array and then loop through the city array to get the properties of each element in that array like this:

var data = {
    "temperatures": {
        "city": [{
            "name": "Riyadh",
            "high": [35, 38, 32]
        }, {
            "name": "New York",
            "high": [28, 36]
        }, {
            "name": "Dubai",
            "high": [18, 20]
        }]
    }
}

var cityArray = data.temperatures.city;
for (var i = 0; i < cityArray.length; i++) {
    // cityArray[i].name   (name of city)
    // cityArray[i].high   (array of high values for that city)
}

if you are using jQuery you can loop through the json elements as

jQuery.getJSON('js/jsonTest.js',function(data) {
    $.each(data, function(key, val) {
        if (key == 'general') { 
            // code here
        } 
     }
}
Post a comment

comment list (0)

  1. No comments so far