简体   繁体   English

遍历Javascript中的JSON数组

[英]Loop through JSON array in Javascript

I have a JSON array which is returned from my PHP ajax call. 我有一个JSON数组,该数组是从我的PHP ajax调用返回的。 I need to loop through it and display all the information. 我需要遍历它并显示所有信息。 I can not seem to get a method working. 我似乎无法找到一种有效的方法。 I am used to using the foreach key => value, in PHP but that doesn't seem to be an option here. 我习惯在PHP中使用foreach键=>值,但这在这里似乎不是一个选择。

my array is 我的数组是

[{"Type":"Person","Durable":"Durable","Url":"test.com"},
{"Type":"Person","Durable":"Durable","Url":"test2.com"},
{"Type":"Person","Durable":"Durable","Url":"test3.com"},
{"Type":"Person","Durable":"Durable","Url":"test4.com"},
{"Type":"Location","Durable":"Durable","Url":"test5.com"},
{"Type":"Phone","Durable":"Durable","Url":"test6.com"}]

The length of the array changes every time it is not always 6 items. 数组的长度每次不总是6个项目时都会更改。 And the loop is going to go in my success handler. 循环将在我的成功处理程序中进行。 I just need help on how to access the data. 我只需要有关如何访问数据的帮助。

success: function(data){

}

You can use a simple loop statement: 您可以使用一个简单的循环语句:

   success: function(data){
    var i, l;
    for (i = 0, l = data.length; i < l; i++) { 
        // access the object: data[i]
        console.log(data[i]);
    }
  }

This is the most effiecient way. 这是最有效的方法。

You can just loop through the array: 您可以遍历数组:

success: function(data){
  for (var i = 0; i < data.length; i++) { 
    var obj = data[i];
    var type = obj.Type;
    var durable = obj.Durable;
    var url = obj.Url;
    // do work
  }
}

You can use the array prototype forEach : 您可以使用数组原型forEach

data.forEach(function(item) {
    var type = item["Type"];
    var durable = item["Durable"];
    /*...*/
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM