我有一个json对象,它是一个数组数组。它看起来像这样:
[{county: Adams, candidate: Smith, votes: 5},
{county: Adams, candidate: Jones, votes: 1},
{county: Clay, candidate: Jones, votes: 7},
{county: Clay, candidate: Smith, votes: 5},
{county: York, candidate: Jones, votes: 10},
{county: York, candidate: Smith, votes: 9}]
对阵列进行排序,使每个选票最多的县的候选人成为该县的第一个项目。
我想过滤数组,只显示每个县与得票最多的候选人。
最好的方法是什么?我尝试使用pop()来删除具有相同县名的项目,但pop只删除数组中的最后一项。我正在寻找拼接,但我不确定是否有更简单的方法来做到这一点。
jquery的:
$.ajax({
url: "myquerypage.php",
method: "POST",
success: function(data) {
var obj = jQuery.parseJSON(data); //this is my json array of rows from the dB
var obj2 = obj; //I made a copy of the original json array
var testString = obj2[0].county;
for (var i = 0; i < obj2.length; i++) {
if (obj2[i].county == testString) {
obj2[i].pop(); //this is wrong
} else {
testString = obj2[i].county;
}
}
console.log(obj2);
});
答案 0 :(得分:0)
您可以使用reduce这样的功能
$.ajax({
url: "myquerypage.php",
method: "POST",
success: function(data) {
var obj = jQuery.parseJSON(data); //this is my json array of rows from the dB
var distinctObj = obj.reduce(
function(acc, el){
var county = acc.set[el.county];
if (county === undefined){
acc.set[el.county] = county = {};
}
if(county.candidate === undefined){
acc.result.push(el);
county.candidate = el;
county.index = acc.result.length-1;
}else if(county.candidate.votes < el.votes){
county.candidate = el;
acc.result[county.index] = county.candidate;
}
return acc;
},{set:{},result:[]}).result;
//console.log(distinctObj);
console.log(JSON.stringify(distinctObj));
});
<强>更新强>
输出所有信息,你可以使用这样的东西
distinctObj.forEach(function(el){
console.log(JSON.stringify(el));
});
OR
console.log(JSON.stringify(distinctObj));
答案 1 :(得分:0)
这是underscore版本(fiddle):
// The output
var results = [];
// Get a list of the unique countys
var countys = _.uniq(_.pluck(arr, 'county'));
// Iterate over the unique countys
_.each(countys, function(county) {
// Find all the results for this county and save the one with the most votes
results.push(_.max(_.where(arr, { county: county }), function(result) {
return result.votes;
}));
});
console.log(results);
你可能比用下划线做得更光滑 - 这对于这类事情非常有利,并且正如评论中所提到的,如果你要做的话,值得进一步研究很多数据操作。