180

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

しかし、何らかの理由で、最初の部分の id 1 値しか取得していません。

何か案は?

4

14 に答える 14

18
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);
});
于 2017-07-10T16:24:34.793 に答える
6

反復処理する場合は、配列でなければなりません。あなたは行方不明[である可能性が非常に高いです].

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/

于 2013-08-14T17:25:39.937 に答える
5

とても簡単な方法です!

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

ありがとうございました。

于 2021-06-18T10:49:06.793 に答える
5

少し遅れましたが、他の人を助けることができるといいのですが:D

あなたのjsonは、ニクラスがすでに言ったことのように見える必要があります。そして、ここに行きます:

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]);
            }
       }
}
于 2015-02-13T11:02:09.440 に答える