1
var data1=[
    {"year":2000,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    },
    {"year":2005,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    },
    {"year":2000,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Net Income - National Currency (millions)"
    },
    {"year":2005,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Net Income - National Currency (millions)"
    }
]

これは、underscorejsを使用してこのように実行したい私のjsonデータです

{
  "key":"Madagascar"
  "values":[
    {"year":2000,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    },
    {"year":2005,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    }
  ]
}

underscore.jsを使用してこの問題を解決するのを誰かが助けてくれますか?

4

1 に答える 1

0

アンダースコアには_.groupBy()メソッドがあり、手間のかかる作業を行うことができますが、値ごとにキーを持つオブジェクトを作成します。

var groupedData1 = _.groupBy(data1, 'country');

groupedData1の値は次のとおりです。

{"Madagascar": [
    {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, 
    {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, 
    {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }, 
    {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }
]}

キー/値の配列に変換するには、_。each()および_.keys()を使用して各国を反復処理できます。

var groupedData2 = [];

_.each(_.keys(groupedData1), function (country) {
    groupedData2.push({
        "key": country, 
        "values": groupedData1[country]
    });
});

これにより、国ごとに1つのオブジェクトの配列が作成されます。

[{
    "key": "Madagascar",
    "values": [{
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }, {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }]
}] 
于 2013-04-02T18:06:11.010 に答える