JavaScript 循环遍历 json 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18238173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript loop through json array?
提问by Alosyius
I am trying to loop through the following json array:
我正在尝试遍历以下 json 数组:
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
And have tried the following
并尝试了以下
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}
But for some reason i am only getting the first part, id 1 values.
但出于某种原因,我只得到了第一部分,id 1 值。
Any ideas?
有任何想法吗?
回答by Niklas
Your JSON should look like this:
您的 JSON 应如下所示:
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
You can loop over the Array like this:
您可以像这样循环遍历数组:
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
Or like this (suggested from Eric) be careful with IE support
或者像这样(来自 Eric 的建议)小心 IE 支持
json.forEach(function(obj) { console.log(obj.id); });
回答by The Dark Knight
There's a few problems in your code, first your json must look like :
您的代码中存在一些问题,首先您的 json 必须如下所示:
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
Next, you can iterate like this :
接下来,您可以像这样迭代:
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(json[key].id);
alert(json[key].msg);
}
}
And it gives perfect result.
它给出了完美的结果。
See the fiddle here : http://jsfiddle.net/zrSmp/
请参阅此处的小提琴:http: //jsfiddle.net/zrSmp/
回答by Sivanesh S
var arr = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
];
forEach method for easy implementation.
forEach 方法,便于实现。
arr.forEach(function(item){
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
回答by chirag sorathiya
try this
尝试这个
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
json.forEach((item) => {
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
回答by surfmuggle
Since i already started looking into it:
因为我已经开始研究它:
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}]
And this function
还有这个功能
var iterateData =function(data){ for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}};
You can call it like this
你可以这样称呼
iterateData(data); // write 1 and 2 to the console
Update after Erics comment
埃里克评论后更新
As ericpointed out a for inloop for an array can have unexpected results. The referenced question has a lengthy discussion about pros and cons.
正如eric指出的,数组的for in循环可能会产生意想不到的结果。引用的问题对利弊进行了冗长的讨论。
Test with for(var i ...
使用 for(var i ...
But it seems that the follwing is quite save:
但似乎以下内容非常节省:
for(var i = 0; i < array.length; i += 1)
Although a test in chrome had the following result
虽然在 chrome 中的测试有以下结果
var ar = [];
ar[0] = "a";
ar[1] = "b";
ar[4] = "c";
function forInArray(ar){
for(var i = 0; i < ar.length; i += 1)
console.log(ar[i]);
}
// calling the function
// returns a,b, undefined, undefined, c, undefined
forInArray(ar);
Test with .forEach()
测试 .forEach()
At least in chrome 30 this works as expected
至少在 chrome 30 中,这按预期工作
var logAr = function(element, index, array) {
console.log("a[" + index + "] = " + element);
}
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c
Links
链接
- see
for inat the mdn - the new forEachmethod
- a comment that states that array comprehension makes
for inless bad - Array comprehensionintroduced with javascript 1.7 in firefox 2 (yes 2)
for in在 mdn 上看到- 新的forEach方法
- 一条评论指出数组理解
for in不那么糟糕 - 在 Firefox 2 中使用 javascript 1.7 引入的数组理解(是 2)
回答by Shyam Shinde
It is working. I just added square brackets to JSON data. The data is:
这是工作。我只是在 JSON 数据中添加了方括号。数据是:
var data = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
]
And the loop is:
循环是:
for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}
回答by lpiepiora
It must be an array if you want to iterate over it. You're very likely missing [and ].
如果要迭代它,它必须是一个数组。你很可能错过了[和]。
var x = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
var $output = $('#output');
for(var i = 0; i < x.length; i++) {
console.log(x[i].id);
}
Check out this jsfiddle: http://jsfiddle.net/lpiepiora/kN7yZ/
看看这个 jsfiddle:http: //jsfiddle.net/lpiepiora/kN7yZ/
回答by Kami Yang
A bit late but i hope i may help others :D
有点晚了,但我希望我可以帮助别人:D
your json needs to look like something Niklas already said. And then here you go:
你的 json 需要看起来像 Niklas 已经说过的东西。然后你开始:
for(var key in currentObject){
if(currentObject.hasOwnProperty(key)) {
console.info(key + ': ' + currentObject[key]);
}
}
if you have an Multidimensional array, this is your code:
如果你有一个多维数组,这是你的代码:
for (var i = 0; i < multiDimensionalArray.length; i++) {
var currentObject = multiDimensionalArray[i]
for(var key in currentObject){
if(currentObject.hasOwnProperty(key)) {
console.info(key + ': ' + currentObject[key]);
}
}
}
回答by Katana314
Well, all I can see there is that you have two JSON objects, seperated by a comma. If both of them were inside an array ([...]) it would make more sense.
好吧,我只能看到您有两个 JSON 对象,用逗号分隔。如果它们都在数组 ( [...]) 中,那就更有意义了。
And, if they ARE inside of an array, then you would just be using the standard "for var i = 0..." type of loop. As it is, I think it's going to try to retrieve the "id" property of the string "1", then "id" of "hi", and so on.
而且,如果它们在数组内,那么您将只使用标准的“for var i = 0...”类型的循环。事实上,我认为它将尝试检索字符串“1”的“id”属性,然后是“hi”的“id”,依此类推。
回答by user2314737
A short solution using mapand an arrow function
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));
And to cover the cases when the property "id"is not present use filter:
并涵盖"id"不存在财产的情况,请使用filter:
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}, {
"msg": "abcde",
"tid": "2013-06-06 23:46",
"fromWho": "[email protected]"
}];
data.filter(item=>item.hasOwnProperty('id'))
.map((item, i) => console.log('Index:', i, 'Id:', item.id));

