获得第一个JSON属性 [英] Getting first JSON property

查看:97
本文介绍了获得第一个JSON属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获取JSON对象的第一个属性的名称?

Is there a way to get the name of the first property of a JSON object?

我想做这样的事情:

var firstProp = jsonObj[0];

编辑:我收到的JSON对象包含数组类别图片网址。

edit: I'm getting a JSON object wich hold categories of arrays with image urls.

如下:

{
  "category1":["image/url/1.jpg","image/url/2.jpg"],
  "category2":["image/url/3.jpg","image/url/4.jpg"]
}

然后我在对象中迭代插入图像和我真正想要的只是一种优雅的方式来查看首先插入的类别。起初我刚刚做了

I am then iterating through the object to insert the images, and all I really wanted was an elegant way to see which category was inserted first. At first I just did

for (var cat in images) {
    if (i==0) firstCat = cat;
    ...
}

但有些人觉得觉得难看。 ..所以它基本上只是一个优雅的问题:p

But that some how "felt" ugly...So it was basically just a question of elegance :p

推荐答案

对象属性的顺序不是保证与放入它们的方式相同。但实际上,所有主流浏览器都会按顺序返回它们。所以如果你依赖这个就好了...

The order of the properties of an object are not guaranteed to be the same as the way you put them in. In practice, however, all major browsers do return them in order. So if you're okay with relying on this...

var firstProp;
for(var key in jsonObj) {
    if(jsonObj.hasOwnProperty(key)) {
        firstProp = jsonObj[key];
        break;
    }
}

另请注意, Chrome中的错误关于订购,在某些边缘情况下,它没有按照提供的方式对其进行排序。至于它在未来的变化,实际上机会实际上很小,因为我相信这已经成为标准的一部分,所以如果对此的任何支持只会变成正式的。

Also note that there's a bug in Chrome regarding the ordering, in some edge cases it doesn't order it in the way they were provided. As far as it changing in the future, the chances are actually pretty small as I believe this is becoming part of the standard so if anything support for this will only become official.

但是,考虑到所有事情,如果你真的,真的,绝对地,积极地,想要确定它将以正确的顺序使用你需要使用数组。否则,上述情况很好。

All things considered, though, if you really, really, absolutely, positively, want to be sure it's going to be in the right order you need to use an array. Otherwise, the above is fine.

相关问题:元素顺序 - 用于javascript中的(... in ...)循环

这篇关于获得第一个JSON属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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