2
var data1 = [
    {"year":2000,"country":"Madagascar","country_id":847,"group":"Economic Statistics "},
    {"year":2005,"country":"Madagascar","country_id":847,"group":"Economic Statistics "},
    {"year":2000,"country":"Madagascar","country_id":847,"group":"Economic Statistics "},
    {"year":2005,"country":"Libya","country_id":846,"group":"Demographic  and Social Statistics "},
    {"year":2008,"country":"Libya","country_id":846,"group":"Demographic  and Social Statistics "},
    {"year":2005,"country":"Libya","country_id":846,"group":"Demographic  and Social Statistics "}
]

This is my JSON data, I want filter it based on country, and year(unique) using underscore.js

4

1 に答える 1

3

いくつかのキーに基づいて一意の要素を選択する場合は、_.uniq(または_.unique) メソッドを使用できます。オプションでコールバックを使用して、比較のために要素をそのキーに変換します。同じ内容の配列は異なるものとして比較されるため、おそらく ke を文字列化する必要があります。JSON.stringifyこれに使用できます(または+- を結果とともに使用できます):

data1=_.uniq(data1, function(x){
    return JSON.stringify([x.year, x.country_id])
});

デモ: http://jsfiddle.net/honnza/xGr9e/

yearとの特定の値を持つ値のみを保持したい場合country_id、これはさらに簡単です。

data1=_.filter(data1, function(x){
    return x.year === target_year && x.country_id === target_country_id
});
于 2013-03-21T09:26:34.147 に答える