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

一連のルックアップを行うことになるため、配列を使用した最終的な構造ではなく、オブジェクトのコレクションを使用することをお勧めします。その後、それを最終的な構造に変換するか、コードを変更してそのまま使用することができます。

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 に答える