2010-01-01 110 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); 
    }); 
});