How To Iterate Json Object With Jquery
I want to iterate this kind of JSON: { 'object': { 'array1': { 'id': 1 }, 'array2': { 'id': 2 } } } I've attempted to use this: for (var i in dicti
Solution 1:
I've searched everywhere and can't find an answer that I want. Seriously? Didn't see what $.each
does?
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);
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
AJAX
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);
});
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Solution 2:
var objectData = {
"object": {
"array1": {
"id": 1
},
"array2": {
"id": 2
}
}
};
$.each(objectData, function(key, data){
// Do stuff here
});
To use this with json from a URL:
$.ajax({
url: URL,
dataType: 'jsonp',
success: function(json) {
$.each(json, function(key, data){
console.log(key);
console.log(data);
});
}
});
Solution 3:
try the following
var d={
"object": {
"array1": {
"id": 1
},
"array2": {
"id": 2
}
}
}
$.each(d,function(i,v){console.log(i,v)})
Post a Comment for "How To Iterate Json Object With Jquery"