使用underdescore.js过滤

时间:2013-03-21 08:38:15

标签: underscore.js

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 "}
]

这是我的JSON数据,我希望根据国家/地区进行过滤,使用underscore.js年份(唯一)

1 个答案:

答案 0 :(得分:3)

如果要根据某个键选择唯一元素,可以使用_.uniq(或_.unique)方法。它可选地进行回调以将元素转换为其键以进行比较。具有相同内容的数组比较不同,因此您可能需要对您的ke进行字符串化; JSON.stringify可以用于此(或者您可以使用+ - 带来后果):

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

演示:http://jsfiddle.net/honnza/xGr9e/

如果您只想保留yearcountry_id的某些特定值的值,则更容易:

data1=_.filter(data1, function(x){
    return x.year === target_year && x.country_id === target_country_id
});