Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through deeply nested json object

     var City ={
"City1": [{"name": "Place 1"},{"name": "Place 2"},{"name": "Place 3"}],
"City2":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}],
"City3":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}]
    };

I want to use JavaScript to loop to get the first city name, and then loop to get its places, then get the second city and its places and so on.

like image 533
Ahmed Elshorbagy Avatar asked Jan 29 '26 12:01

Ahmed Elshorbagy


1 Answers

You could use a for loop to go through all properties of the City object:

for (var key in City) {
    if (City.hasOwnProperty(key)) {
        var values = City[key];
        // "key" will be City1, City2, ...
        // "values" will be the corresponding array through which
        // you can loop
    }
}
like image 143
Darin Dimitrov Avatar answered Feb 01 '26 01:02

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!