通过 JSON 数组的 JavaScript 循环?

我尝试循环访问下面的 json 数组:

{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}

并尝试以下方法

for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}

但由于某种原因,我只得到了第一部分,id1值。

有什么想法吗?

742009 次浏览

我所能看到的就是有两个 JSON 对象,用逗号分隔。如果它们都在一个数组([...])中,那就更有意义了。

而且,如果它们在一个数组中,那么您只需要使用标准的“ for var i = 0...”循环类型。实际上,我认为它将尝试检索字符串“1”的“ id”属性,然后检索“ hi”的“ id”,以此类推。

您的 JSON 应该是这样的:

let json = [{
"id" : "1",
"msg"   : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2",
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];

你可以像这样在 Array 上循环:

for(let i = 0; i < json.length; i++) {
let obj = json[i];


console.log(obj.id);
}

或者像这样(来自 Eric 的建议)对 IE 支持要小心

json.forEach(function(obj) { console.log(obj.id); });

既然我已经开始调查了:

var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}]

这个函数

var iterateData =function(data){   for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}};

你可以这么说

iterateData(data); // write 1 and 2 to the console

在 Eric 评论后更新

正如 Eric指出的 数组的 for in循环可能会产生意外的结果。引用的问题有一个关于利弊的冗长讨论。

用(var i..。

不过,下面的内容似乎相当保守:

for(var i = 0; i < array.length; i += 1)

虽然铬的测试有以下结果

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);

.forEach()测试

至少在铬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

连结

如果要在它上面迭代,那么它必须是一个数组。

var x = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];


var $output = $('#output');
for(var i = 0; i < x.length; i++) {
console.log(x[i].id);
}

看看这个 jsfiddle: http://jsfiddle.net/lpiepiora/kN7yZ/

这是工作。我只是添加了方括号的 JSON 数据。数据是:

var data = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}
]

循环是:

for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}

在您的代码中有一些问题,首先您的 json 必须看起来像:

var json = [{
"id" : "1",
"msg"   : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2",
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];

接下来,您可以这样迭代:

for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(json[key].id);
alert(json[key].msg);
}
}

它给出了完美的结果。

看这里的小提琴: http://jsfiddle.net/zrSmp/

有点晚了,但我希望我可以帮助别人

你的 Json 得像 Niklas 说过的那样,然后你看:

for(var key in currentObject){
if(currentObject.hasOwnProperty(key)) {
console.info(key + ': ' + currentObject[key]);
}
}

如果你有一个多维数组,这是你的代码:

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]);
}
}
}

使用 map箭头函数的简短解决方案

var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));

为了涵盖属性 "id"不存在的情况,可以使用 filter:

var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}, {
"msg": "abcde",
"tid": "2013-06-06 23:46",
"fromWho": "hello3@email.se"
}];


data.filter(item=>item.hasOwnProperty('id'))
.map((item, i) => console.log('Index:', i, 'Id:', item.id));

var arr = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}
];

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);
});

试试这个

var json = [{
"id" : "1",
"msg"   : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2",
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];


json.forEach((item) => {
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});

您的数据片段需要稍微扩展一下,并且必须以这种方式才能成为正确的 JSON。注意,我只包含了数组名称属性 item

{
"item": [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}]
}

您的 JavaScript 只是

var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
var curitem = json.item[x];
}

非常简单的方法!

var tire_price_data = JSON.parse('[{"qty":"250.0000","price":"0.390000"},{"qty":"500.0000","price":"0.340000"},{"qty":"1000.0000","price":"0.290000"}]');
tire_price_data.forEach(function(obj){
console.log(obj);
console.log(obj.qty);
console.log(obj.price);
})

谢谢你。

var json = {
"persons": [
{"name": "Lili", "age": 23, "is_student": true},
{"name": "James", "age": 24, "is_student": true},
{"name": "John", "age": 25, "is_student": false}
]
};


for (var key in json.persons) {
for (var keyName in json.persons[key]) {
alert(keyName + ': ' + (json.persons[key])[keyName]);
}
}

//输出: name: Lili,age: 23,is _ school: true,..。

您可以使用 for 循环,然后获取值,您可以解构它们

const arr = [
{
id:123,
desc:"do something",
isDone:false
},
{
id:124,
desc:"do something",
isDone:true
}
]


for(let _i in arr){
let {id, desc, isDone} = arr[_i]
// do something
console.log({id, desc, isDone});
}