我有以下JSON结构:

[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]

我如何使用JavaScript迭代它?


当前回答

var jsonString = `{ "schema": { "title": "User Feedback", "description": "so", "type": "object", "properties": { "name": { "type": "string" } } }, "options": { "form": { "attributes": {}, "buttons": { "submit": { "title": "It", "click": "function(){alert('hello');}" } } } } }`; var jsonData = JSON.parse(jsonString); function Iterate(data) { jQuery.each(data, function (index, value) { if (typeof value == 'object') { alert("Object " + index); Iterate(value); } else { alert(index + " : " + value); } }); } Iterate(jsonData); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

其他回答

另一个在JSON文档中导航的解决方案是JSONiq(在Zorba引擎中实现),在那里你可以写这样的东西:

let $doc := [
  {"id":"10", "class": "child-of-9"},
  {"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class         (: gets the value associated with "class" :)

您可以在http://public.rumbledb.org:9090/public.html上运行它

你可以使用像objx - http://objx.googlecode.com/这样的迷你库

你可以这样写代码:

var data =  [ {"id":"10", "class": "child-of-9"},
              {"id":"11", "class": "child-of-10"}];

// alert all IDs
objx(data).each(function(item) { alert(item.id) });

// get all IDs into a new array
var ids = objx(data).collect("id").obj();

// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()

还有更多的“插件”可以让你这样处理数据,请参阅http://code.google.com/p/objx-plugins/wiki/PluginLibrary

从http://www.w3schools.com复制和粘贴,不需要JQuery开销。

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

结果:无名氏25人

对于嵌套对象,可以通过递归函数检索:

function inside(events)
  {
    for (i in events) {
      if (typeof events[i] === 'object')
        inside(events[i]);
      else
      alert(events[i]);
    }
  }
  inside(events);

其中as events是json object。

王侯的问题可能是使用jQuery时的最佳答案。

下面是纯JavaScript中非常类似的东西,使用JavaScript的forEach方法。forEach以函数作为参数。然后,将为数组中的每个项调用该函数,并将该项作为参数。

简短而简单:

var结果= [{" id ":“10”,“类”:“child-of-9”},{" id ":“十一”,“classd”:“child-of-10”}); results.forEach(函数(项){ console.log(项); });