gpt4 book ai didi

underscore.js - 使用 underdescore.js 过滤

转载 作者:行者123 更新时间:2023-12-04 05:05:38 24 4
gpt4 key购买 nike

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 过滤它

最佳答案

如果要根据某个键选择唯一元素,可以使用 _.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
});

关于underscore.js - 使用 underdescore.js 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15542711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com