通过索引检索JSON对象的属性? [英] Retrieving a property of a JSON object by index?
问题描述
假设这个JSON对象:
Assuming this JSON object:
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
可以像这样检索set2属性:
The "set2" property may be retrieved like so:
obj["set2"]
是有没有办法通过索引检索set2属性?它是JSON对象的第二个属性。这当然不起作用:
Is there a way to retrieve the "set2" property by index? It is the second property of the JSON object. This does not work (of course):
obj[1]
所以,我想说我想要检索JSON对象的第二个属性,但我不知道它的名字 - 那我该怎么做呢?
So, let's say that I want to retrieve the second property of the JSON object, but I don't know its name - how would I do it then?
更新: 是的,我知道对象是无序属性的集合。但我不认为浏览器会混淆JSON文字/字符串定义的原始顺序。
Update: Yes, I understand that objects are collections of unordered properties. But I don't think that the browsers mess with the "original" order defined by the JSON literal / string.
推荐答案
对象在JavaScript中是无序属性的集合。对象是哈希表。
Objects in JavaScript are collections of unordered properties. Objects are hashtables.
如果您希望属性按字母顺序排列,一种可能的解决方案是在单独的数组中为属性创建索引。就在几个小时前,我回答了一个关于Stack Overflow的问题你可能想看看:
If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:
- Iterating over a JavaScript object in sort order based on particular key value of a child object
这是一个快速适应你的对象 1 :
Here's a quick adaptation for your object1:
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
var index = [];
// build the index
for (var x in obj) {
index.push(x);
}
// sort the index
index.sort(function (a, b) {
return a == b ? 0 : (a > b ? 1 : -1);
});
然后你可以做到以下几点:
Then you would be able to do the following:
console.log(obj[index[1]]);
我引用的答案早先提出了一个可重用的解决方案来迭代这样的对象。除非您可以将JSON更改为 @Jacob Relkin在另一个答案中建议,这可能会更容易。
The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.
1 您可能想使用 hasOwnProperty()
方法,以确保属性属于您的对象,并且不从 Object.prototype
继承。
1 You may want to use the hasOwnProperty()
method to ensure that the properties belong to your object and are not inherited from Object.prototype
.
这篇关于通过索引检索JSON对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!