3

I am meeting now the difficult problem for me that hurt my heart, I want to convert [01] JSON to [02].

[01] JSON :

{locations: [
    {
        country: "Australia",
        area: "NSW",
        city: "Gordon"
    },
    {
        country: "Australia",
        area: "NSW",
        city: "Chatswood"
    }
]};

[02] JSON :

{countries: [
    {
        name: "Australia",
        areas: [
            {
                 name: "NSW",
                 cities: [
                      {
                           name: "Gordon"
                      },
                      {
                           name: "Chatswood"
                      }
                 ]
            }
        ]
    } 
]}
4

1 回答 1

1

Since you're going to be doing a bunch of lookups I suggest using a collection of objects rather than your final structure with arrays. You can then either convert it to the final structure or modify code to use it the way it is.

var countries = {};
for (var i=0, loc; loc = locations[i]; i++) {
    if (!countries[loc.country]) countries[loc.country] = {};
    if (!countries[loc.country][loc.area]) countries[loc.country][loc.area] = [];
    countries[loc.country][loc.area].push(loc.city);
}
alert(JSON.stringify(countries));
于 2013-02-18T02:26:36.480 回答