I have my JSON as follows

{"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中找出distinct name

Result javascript,jquery,ajax

我可以用下面的方法

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++;
  }
}

有没有better method个能给我更好的表现?

推荐答案

如果您想节省一些周期,我会使用一个对象和一个数组:

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

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.

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相关问答推荐

为什么terraform不缩小这个策略JSON?'

Golang返回的JSON顶级字段是可变的.如何在 struct 中使用

Flutter -控制器问题-JSON API

在MongoDB中检索某个月份和年份的JSON文档

给定一个包含两个数组的JSON输入文件,如何使用Jolt将一个数组中的每个元素与另一个数组组合在一起?

无法使用Jolt变换在嵌套的JSON中提取值

规范化JSON数据

在 SQL 存储过程中使用参数 Select 值

展平多个数组以保持顺序

使用 jq 和脚本 bash 映射两个 json

将请求中的数据推送到数组中

将 colly 包输出文本添加到 golang 中的映射

JOLT 在 struct 体中间添加一个 JSON 字段

从 json 数组中仅提取一个值导致 vb6

如何判断 Json 对象中是否存在键并获取其值

如何使用 CORS 实现 JavaScript Google Places API 请求

Golang struct 的 XML 和 JSON 标签?

如何安装 json gem - 无法构建 gem 原生扩展(mac 10.10)

POST:在 url 本身中发送 post 请求

jq:按属性分组和键