簡體   English   中英

JavaScript循環遍歷JSON數組?

[英]JavaScript loop through JSON array?

我正在嘗試遍歷以下 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 值。

有任何想法嗎?

您的 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"
}];

您可以像這樣循環數組:

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

您的代碼中有一些問題,首先您的 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/

嘗試這個

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);
});
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 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指出的那樣,數組的for in循環可能會產生意想不到的結果 引用的問題對利弊進行了冗長的討論。

用 for(var i ...

但似乎以下內容非常節省:

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

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

使用.forEach()進行測試

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

鏈接

這是工作。 我只是在 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。 請注意,我只包含數組名稱屬性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 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 對象,用逗號分隔。 如果它們都在一個數組( [...] )內,那將更有意義。

而且,如果它們在數組內,那么您將只使用標准的“for var i = 0 ...”類型的循環。 事實上,我認為它將嘗試檢索字符串“1”的“id”屬性,然后檢索“hi”的“id”,等等。

有點晚了,但我希望我可以幫助別人:D

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

非常簡單的方法!

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_student:true, ...

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

您可以使用 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});
}


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM