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

这是我的 JSON 数据,我想根据国家和年份(唯一)过滤它underscore.js

4

1 回答 1

3

如果要根据某个键选择唯一元素,可以使用_.uniq(or _.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
});
于 2013-03-21T09:26:34.147 回答