如何通过索引访问JSON对象中的字段 [英] How to access fields in JSON object by index

查看:408
本文介绍了如何通过索引访问JSON对象中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这不是最好的方法,但是我别无选择:(

I know this isn't the best way to do it, but I have no other choice :(

我必须按其索引访问JSONObject中的项目.访问对象的标准方法是只写this[objectName]this.objectName.我还找到了一种获取json对象内所有字段的方法:

I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:

(for (var key in p) { 
  if (p.hasOwnProperty(key)) { 
    alert(key + " -> " + p[key]); 
  } 
} 

(解决方案:通过Json对象循环).

但是,无法通过索引直接访问JSONfields.我现在看到的唯一方法是,使用上面的函数创建一个数组,按索引获取字段名称,然后按字段名称获取值.

However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.

据我所知,p(在我们的例子中,JSON文件必须是可迭代的数组,否则foreach循环将无法工作.如何直接访问此数组?或者是某种形式未排序的列表?

As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?

推荐答案

JSON对象更像是键-值映射.所以,是的,它是未分类的.解决这个问题的唯一方法是已经提到的index->​​ property名称映射:

A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:

var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)
    alert(object[keysbyindex[i]]);

但是为什么需要这些索引?与Array一样,未排序的映射也没有length属性.为什么不使用循环中的

But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop

var counter = 0; // if you need it
for (var key in object) {
    alert(object[key])
    counter++;
}

?如果您具有已解析的JSON对象(即普通的JS对象),则无需担心枚举的原型属性.

? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.

这篇关于如何通过索引访问JSON对象中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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