从JSON中选择不同的值 [英] Selecting distinct values from a JSON

查看:71
本文介绍了从JSON中选择不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON如下

{"DATA": [{"id":11,"name":"ajax","subject":"OR","mark":63},
{"id":12,"name":"javascript","subject":"OR","mark":63},
{"id":13,"name":"jquery","subject":"OR","mark":63},
{"id":14,"name":"ajax","subject":"OR","mark":63},
{"id":15,"name":"jquery","subject":"OR","mark":63},
{"id":16,"name":"ajax","subject":"OR","mark":63},
{"id":20,"name":"ajax","subject":"OR","mark":63}],"COUNT":"120"}

有没有什么好方法可以从这个JSON中找出不同名称

Is there any good method to find out the distinct name from this JSON

结果 javascript,jquery,ajax

我可以使用以下方法做到这一点

I can do this using following methode

var arr=[''];
var j=0;
for (var i = 0; i < varjson.DATA.length; i++) {
  if($.inArray(varjson.DATA[i]["name"],arr)<0){
      arr[j]=varjson.DATA[i]["name"];
      j++;
  }
}

是否有更好的方法这给了我更好的表现?

Is there any better method which gave me better performance?

推荐答案

我会使用一个对象和一个数组,如果你想要的话保存一些周期:

I would use one Object and one Array, if you want to save some cycle:

var lookup = {};
var items = json.DATA;
var result = [];

for (var item, i = 0; item = items[i++];) {
  var name = item.name;

  if (!(name in lookup)) {
    lookup[name] = 1;
    result.push(name);
  }
}

这样你就基本上避免了 indexOf / inArray 调用,你将获得一个可以迭代比迭代对象属性更快的数组 - 也因为在第二个如果你需要检查 hasOwnProperty

In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.

当然如果你对一个对象没问题你可以避免检查和 result.push ,如果使用 Object.keys(查找)获取数组,但是它不会比那更快。

Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.

这篇关于从JSON中选择不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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