如何使用jQuery迭代JSON对象 [英] How to iterate JSON object with jQuery
问题描述
我想迭代这种JSON:
I want to iterate this kind of JSON:
{
"object": {
"array1": {
"id": 1
},
"array2": {
"id": 2
}
}
}
我尝试使用此功能:
for (var i in dictionary) {
console.log(dictionary[i].id);
}
但不起作用.
推荐答案
我到处搜索,找不到想要的答案.认真吗?没看到 $.each
做什么?
I've searched everywhere and can't find an answer that I want. Seriously? Didn't see what $.each
does?
一个通用的迭代器函数,可用于对对象和数组进行无缝迭代.具有长度属性的数组和类似数组的对象(例如函数的arguments对象)通过从0到length-1的数字索引进行迭代.其他对象通过其命名属性进行迭代.
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
var arr = {
"object": {
"array1": {
"id": 1
},
"array2": {
"id": 2
}
}
};
$.each(arr, function (i, v) {
console.log(i);
console.log(v);
$.each(v, function (idx, val) {
console.log(idx);
console.log(val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
AJAX
如果您使用AJAX来获取JSON,则可以很好地使用:$.getJSON
:
If you are using AJAX to fetch the JSON, you can very well use: $.getJSON
:
$.getJSON("https://cdn.rawgit.com/fge/sample-json-schemas/master/avro/avro-schema.json", function (res) {
$.each(res, function (i, v) {
console.log(i);
console.log(v);
if (typeof v == "object")
$.each(v, function (idx, val) {
console.log(idx);
console.log(val);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于如何使用jQuery迭代JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!