2

I have a JSON object of arrays

data = {
   China: ["Guangzhou","Fax"],
   Majorette: ["Fungous","Godzilla"],
   Bhutan: ["Thimphu","Parr","Photofinishing"]
}

I want to access name of cities in an array without explicitly mentioning the name of countries as list is very long.

var cities = [];
for(var i in data.China) {
   cities[i] = data.China[i];
}

How should I do for all the countries?

1
  • You want to flatten the array of cities? Commented Jan 5, 2015 at 12:38

4 Answers 4

2

This should populate the cities array:

var data = {
China: ["Guangzhou","Fax"],
Majorette: ["Fungous","Godzilla"],
Bhutan: ["Thimphu","Parr","Photofinishing"]
}

var cities = [];
for(var i in data){
    if(data.hasOwnProperty(i)){
        for(var j in data[i] ){
             if(data[i].hasOwnProperty(j)){
                cities.push(data[i][j]);
             }
        }
    }

}

console.log(cities);

JSFIDDLE Demo

Sign up to request clarification or add additional context in comments.

6 Comments

Note that you can use [] in place of new Array and that a loop that pushes things is just a array.map.
Good, now note that some browsers like IE8 don't have a notion of enmerable and non-enumerable properties so when you iterate an array with a for... in you'll get an extra key for the .length for example. This means you should wrap that code in a hasOwnProperty check. See javascript.crockford.com/code.html
good findings @BenjaminGruenbaum. Learned something. updated.
Great, I've removed my downvote. Now - please consider that iterating arrays with for... in loops is considered bad practice since the iteration order is not guaranteed. To be fair OP did not ask for it here so it's not a huge deal but using data[i].forEach or even better data[i].map could make your core shorter and potentially more correct.
If you modify your code to not nest 5 levels and explain why it's written this way (vs your original revision) I'll gladly upvote this answer.
|
2

To iterate over the cities object effectively:

Object.keys(data).forEach(function(key) {
    // In here, data[key] is each array of cities.
});

Now, from what I understand from your question, you want to reduce the multidimensional object/array to one flat array of cities:

var cities = Object.keys(data).reduce(function(arr, key) {
    return arr.concat(data[key]);
}, []);

Please note that Object.keys, as well as Array.prototype.forEach and Array.prototype.reduce are IE9 and above functions.

1 Comment

@PraffulGupta You're welcome. Note that you can accept the answer (and thus marking it as "complete") that solved your problem by click on the large tick mark below the question's score. Only use it if the answer really solved your problem though.
-1
for (var key in data) {
    var citiesArray = data[key]; // cities for the current country
    // your code

}

1 Comment

@SecondRikudo I'm pretty sure .length is not enumerable. That said it will count it in old browsers like IE8
-1
 for (var country in data){
    for(var i=0;i<data[country].length;i++){
        console.log (data[country][i]);   
    } 
}

1 Comment

Thanks Peter, it will print all the cities to console, but it should also have following code to append the cities. cities.push(data[country][i]);

Your Answer

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.