2010-01-01 109 views
2

我有JSON對象的數組,像這樣:在JSON數組獲取值的對象

[ 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" } 
] 

我想通過他們循環和回聲出來在列表中。我該怎麼做?

+0

只是添加,那裏有沒有什麼特別的JSON。它只是一個JavaScript對象初始化圖..在你的例子中你有一個數組(方括號),其中的對象(大括號語法)..你應該檢查出對象和數組文字在JavaScript中揭示'魔術' – meandmycode 2010-01-01 11:41:17

回答

6

你的意思是這樣的嗎?

var a = [ 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" } 
]; 

function iter() { 
    for(var i = 0; i < a.length; ++i) { 
     var json = a[i]; 
     for(var prop in json) { 
       alert(json[prop]); 
          // or myArray.push(json[prop]) or whatever you want 
     } 
    } 
} 
2
var json = [ 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" } 
] 

for(var i in json){ 
    var json2 = json[i]; 
    for(var j in json2){ 
     console.log(i+'-'+j+" : "+json2[j]); 
    } 
} 
1

另一種解決方案:

var jsonArray = [ 
    { name: "Alice", text: "a" }, 
    { name: "Bob", text: "b" }, 
    { name: "Carol", text: "c" }, 
    { name: "Dave", text: "d" } 
]; 

jsonArray.forEach(function(json){ 
    for(var key in json){ 
    var log = "Key: {0} - Value: {1}"; 
    log = log.replace("{0}", key); // key 
    log = log.replace("{1}", json[key]); // value 
    console.log(log); 
    } 
}); 

如果要針對新的瀏覽器,你可以使用Objects.keys

var jsonArray = [ 
    { name: "Alice", text: "a" }, 
    { name: "Bob", text: "b" }, 
    { name: "Carol", text: "c" }, 
    { name: "Dave", text: "d" } 
]; 

jsonArray.forEach(function(json){ 
    Object.keys(json).forEach(function(key){ 
    var log = "Key: {0} - Value: {1}"; 
    log = log.replace("{0}", key); // key 
    log = log.replace("{1}", json[key]); // value 
    console.log(log); 
    }); 
});