[英]How do I filter the unique objects from an array if the filter key can have any type of value?
[英]How can I “filter” JSON for unique key name/value pairs?
我有一些JSON数据给我一个语言列表,其中包含lat / lng等信息。它还包含我用于图标的组值 - 我想用它构建一个图例。 JSON看起来像这样:
{"markers":[
{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}
]}
我想“过滤”它最终像这样:
{"markers":[
{"group":"a", "value":"yes"},
{"group":"b", "value":"no"},
{"group":"c", "value":"NA"}
]}
现在我已经得到了这个,使用jQuery来创建我的传奇......当然,它正在吸引所有的价值观:
$.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){
$.each(json.markers, function(i, language){
$('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents');
});
});
对于给定的对,我怎样才能获取整个JSON对象中的唯一名称/值对?
我将标记数组转换为键值对,然后循环该对象属性。
var markers = [{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}];
var uniqueGroups = {};
$.each(markers, function() {
uniqueGroups[this.group] = this.value;
});
然后
$.each(uniqueGroups, function(g) {
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents');
});
要么
for(var g in uniqueGroups)
{
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents');
}
此代码示例使用循环中的最后一个值覆盖唯一值。 如果您想使用第一个值,则必须执行一些条件检查以查看密钥是否存在。
更通用的东西怎么样?
function getDistinct(o, attr)
{
var answer = {};
$.each(o, function(index, record) {
answer[index[attr]] = answer[index[attr]] || [];
answer[index[attr]].push(record);
});
return answer; //return an object that has an entry for each unique value of attr in o as key, values will be an array of all the records that had this particular attr.
}
不仅这样的函数会返回您指定的所有不同值,而且如果您需要访问它们,它也会对它们进行分组。
在您的示例中,您将使用:
$.each(getDistinct(markers, "group"), function(groupName, recordArray)
{ var firstRecord = recordArray[0];
$('<p>').html('<img src="http://mysite/group' + groupName+ '.png\" />' + firstRecord.value).appendTo('#legend-contents');
}
var markers = _.uniq( _.collect( markers , function( x ){
return JSON.stringify( x );
}));
请参阅此- 查询javascript对象数组中的唯一属性值的最佳方法?
您只需要一个检查2个值而不是1个值的变体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.