我有以下JSON结构:

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

我如何使用JavaScript迭代它?


当前回答

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

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

简短而简单:

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

其他回答

使用的…:

var mycars = [{name:'Susita'}, {name:'BMW'}]; 对于(MyCars的VaR Car) { document.write(car.name + “<br />”); }

结果:

Susita
BMW

取自jQuery文档:

var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {
  $("#" + this).text("My id is " + this + ".");
  return (this != "four"); // will stop running to skip "five"
});

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});

如果不容易,请告诉我:

var jsonObject = {
  name: 'Amit Kumar',
  Age: '27'
};

for (var prop in jsonObject) {
  alert("Key:" + prop);
  alert("Value:" + jsonObject[prop]);
}

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>

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

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

简短而简单:

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