我怎么能和QUOT;滤波器QUOT; JSON独特的键名/值对? [英] How can I "filter" JSON for unique key name/value pairs?

查看:98
本文介绍了我怎么能和QUOT;滤波器QUOT; JSON独特的键名/值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是给我的语言列表中包含纬度/经度信息的一些JSON数据,同时还包括,我使用了图标的群体价值 - 我想建立一个与传说它。该JSON看起来是这样的:

I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this:

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

和我想的过滤器,它落得这样的:

And I want to "filter" it to end up like this:

{"markers":[
 {"group":"a", "value":"yes"},
 {"group":"b", "value":"no"},
 {"group":"c", "value":"NA"}
]}

现在我已经得到了这一点,使用jQuery创建我当然legend..but它拉动所有值:

Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values:

$.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对象,因为是一对?

How can I only grab the unique name/value pairs in the entire JSON object, for a given pair?

推荐答案

我标记数组转换为一个键值对,然后循环对象的属性。

I'd transform the array of markers to a key value pair and then loop that objects properties.

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');
}

这code样本覆盖在循环的最后价值的独特价值。如果你想使用的第一个值,而不是你将不得不执行一些有条件的检查,看是否存在的关键。

This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.

这篇关于我怎么能和QUOT;滤波器QUOT; JSON独特的键名/值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆