[英]How do I loop through this JSON?
我從PHP腳本返回了以下JSON
var data ={
"first thing" :["1","2"],
"second thing" :["5","7"],
"third thing" :["8","2"]
};
我知道我可以像這樣訪問這些項目:
console.log(data["first thing"]);
但是,我需要遍歷它們並將它們應用於某些html,並且對象名稱將發生變化,因此如何使循環系統地遍歷它們並根據需要應用? 基本上,我首先需要遍歷並應用名稱,然后稍后將再次遍歷並應用值對。
processResults:function(data){
$('.thisclass').each(function(){
$(this).html('put first json name here, so "first thing"')
//then continue to loop through and apply next object name
});
}
然后在下一個循環中,我將需要執行以下操作:
processResults:function(data){
$('.nextclass').each(function(){
$(this).html('put first of two values here, so "1"')
//then continue to loop through and apply next object value
});
}
問題是我不知道如何在不使用括號符號指定對象名稱的情況下執行此操作!
您可以嘗試一下(因為它已用jQuery
標記):
$.each(yourObject, function(key, element){
//key will be like "first thing" and so-
//element will be an array.
//it's true that yourObject[key] == element
$.each(element, function(arrayIndex, arrayElement) {
//process each arrayElement here
//it's true that element[arrayIndex] == arrayElement
})
})
var data ={
"first thing" :["1","2"],
"second thing" :["5","7"],
"third thing" :["8","2"]
};
$.each(data, function (key, arr) {
console.log(key);
var i = 0;
for(i; i < arr.length; i++) {
console.log(arr[i]);
}
})
您可以執行以下操作:
var data ={
"first thing" :["1","2"],
"second thing" :["5","7"],
"third thing" :["8","2"]
};
//this will print all the key names
for (var key in data) {
console.log(key);
}
//this will print the key values.
for (var key in data) {
console.log(data[key]);
}
現在,您只需要根據需要進行調整即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.