Javascript 通过索引检索 JSON 对象的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4044845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:14:42  来源:igfitidea点击:

Retrieving a property of a JSON object by index?

javascriptjson

提问by ?ime Vidas

Assuming this JSON object:

假设这个 JSON 对象:

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

The "set2" property may be retrieved like so:

可以像这样检索“set2”属性:

obj["set2"]

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):

有没有办法通过索引检索“set2”属性?它是 JSON 对象的第二个属性。这不起作用(当然):

obj[1]  

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.

更新:是的,我知道对象是无序属性的集合。但我不认为浏览器会混淆 JSON 文字/字符串定义的“原始”顺序。

采纳答案by Daniel Vassallo

Objects in JavaScript are collections of unorderedproperties. Objects are hashtables.

JavaScript 中的对象是无序属性的集合。对象是哈希表。

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:

如果您希望您的属性按字母顺序排列,一种可能的解决方案是在单独的数组中为您的属性创建索引。就在几个小时前,我回答了一个关于 Stack Overflow 的问题,你可能想看看:

Here's a quick adaptation for your object1:

这是对您的对象1的快速改编:

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

The answer I citedearlier 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.

之前引用答案提出了一个可重用的解决方案来迭代这样的对象。除非您可以将 JSON 更改为@Jacob Relkin 在另一个答案中建议的那样,这可能会更容易。



1You may want to use the hasOwnProperty()method to ensure that the properties belong to your object and are not inherited from Object.prototype.

1您可能希望使用该hasOwnProperty()方法来确保属性属于您的对象,而不是从Object.prototype.

回答by Jacob Relkin

No, there is no way to access the element by index in JavaScript objects.

不,无法通过 JavaScript 对象中的索引访问元素。

One solution to this if you have access to the source of this JSON, would be to change each element to a JSON object and stick the key inside of that object like this:

如果您有权访问此 JSON 的源,则解决此问题的一种方法是将每个元素更改为 JSON 对象,并将键粘贴在该对象中,如下所示:

var obj = [
    {"key":"set1", "data":[1, 2, 3]},
    {"key":"set2", "data":[4, 5, 6, 7, 8]},
    {"key":"set3", "data":[9, 10, 11, 12]}
];

You would then be able to access the elements numerically:

然后,您将能够以数字方式访问元素:

for(var i = 0; i < obj.length; i++) {
    var k = obj[i]['key'];
    var data = obj[i]['data'];
    //do something with k or data...
}

回答by Jeroen Vervaeke

I know this is an old question but I found a way to get the fields by index. You can do it by using the Object.keysmethod.

我知道这是一个老问题,但我找到了一种通过索引获取字段的方法。您可以通过使用该Object.keys方法来完成。

When you call the Object.keysmethod it returns the keys in the order they were assigned (See the example below). I tested the method below in the following browsers:

当您调用该Object.keys方法时,它会按照分配的顺序返回键(请参见下面的示例)。我在以下浏览器中测试了以下方法:

  • Google Chrome version 43.0
  • Firefox version 33.1
  • Internet Explorer version 11
  • 谷歌浏览器 43.0 版
  • 火狐版本 33.1
  • Internet Explorer 版本 11

I also wrote a small extension to the object class so you can call the nth key of the object using getByIndex.

我还为对象类编写了一个小扩展,以便您可以使用getByIndex.

// Function to get the nth key from the object
Object.prototype.getByIndex = function(index) {
  return this[Object.keys(this)[index]];
};

var obj1 = {
  "set1": [1, 2, 3],
  "set2": [4, 5, 6, 7, 8],
  "set3": [9, 10, 11, 12]
};

var obj2 = {
  "set2": [4, 5, 6, 7, 8],
  "set1": [1, 2, 3],
  "set3": [9, 10, 11, 12]
};

log('-- Obj1 --');
log(obj1);
log(Object.keys(obj1));
log(obj1.getByIndex(0));


log('-- Obj2 --');
log(obj2);
log(Object.keys(obj2));
log(obj2.getByIndex(0));


// Log function to make the snippet possible
function log(x) {
  var d = document.createElement("div");
  if (typeof x === "object") {
    x = JSON.stringify(x, null, 4);
  }
  d.textContent= x;
  document.body.appendChild(d);
}

回答by Vishant dhandha

Here you can access "set2" property following:

在这里您可以访问“set2”属性如下:

    var obj = {
        "set1": [1, 2, 3],
        "set2": [4, 5, 6, 7, 8],
        "set3": [9, 10, 11, 12]
    };

    var output = Object.keys(obj)[1];

Object.keys return all the keys of provided object as Array..

Object.keys 将提供的对象的所有键返回为 Array..

回答by Faris Mohammed

Simple solution, just one line..

简单的解决方案,只需一行..

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

obj = Object.values(obj);

obj[1]....

回答by Gagik Sargsyan

Jeroen Vervaeke's answer is modular and the works fine, but it can cause problemsif it is using with jQuery or other libraries that count on "object-as-hashtables" feature of Javascript.

Jeroen Vervaeke的答案是模块化的并且工作正常,但是如果它与 jQuery 或其他依赖 Javascript 的“对象作为哈希表”功能的库一起使用,它可能会导致问题

I modified it a little to make usable with these libs.

我对其进行了一些修改以使其可用于这些库。

function getByIndex(obj, index) {
  return obj[Object.keys(obj)[index]];
}

回答by Douglas

You could iterate over the object and assign properties to indexes, like this:

您可以遍历对象并将属性分配给索引,如下所示:

var lookup = [];
var i = 0;

for (var name in obj) {
    if (obj.hasOwnProperty(name)) {
        lookup[i] = obj[name];
        i++;
    }
}

lookup[2] ...

However, as the others have said, the keys are in principle unordered. If you have code which depends on the corder, consider it a hack. Make sure you have unit tests so that you will know when it breaks.

然而,正如其他人所说,键原则上是无序的。如果您的代码依赖于编码器,请将其视为 hack。确保你有单元测试,这样你就会知道它什么时候坏了。

回答by raccoon

"""
This could be done in python as follows.
Form the command as a string and then execute
"""
context = {
    "whoami": "abc",
    "status": "0",
    "curStep": 2,
    "parentStepStatus": {
        "step1":[{"stepStatus": 0, "stepLog": "f1.log"}],
        "step2":[{"stepStatus": 0, "stepLog": "f2.log"}]
    }
}
def punc():
          i = 1
          while (i < 10):
              x = "print(" + "context" + "['parentStepStatus']" + "['%s']"%("step%s")%(i) + ")"
              exec(x)
              i+=1
punc()

回答by Mike Morearty

There is no "second property" -- when you say var obj = { ... }, the properties inside the braces are unordered. Even a 'for' loop walking through them might return them in different orders on different JavaScript implementations.

没有“第二个属性”——当你说的时候var obj = { ... },大括号内的属性是无序的。即使是遍历它们的“for”循环也可能在不同的 JavaScript 实现中以不同的顺序返回它们。

回答by Syed Saad Hussain

it is quite simple...

这很简单...

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

jQuery.each(obj, function(i, val) {
 console.log(i); // "set1"
 console.log(val); // [1, 2, 3]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>