我需要循环该数组

时间:2018-08-16 08:51:24

标签: javascript jquery arrays loops

我使用ajax从Economic中获取数组,但我想循环播放。数组(已排序):

    {   
  "collection": [  
    { "customerNumber": 1, "email": "jo+billing@test.com", "name": "Tester Test" }  
    , { "customerNumber": 2, "name": "Demo Name" }  
    ]  
    , "metaData": { "more array" }  
    , "pagination": { "more array"}  
    , "self": "some url"   
    }

我认为我需要使用的jquery,但给我一个错误:(TypeError:无法使用'in'运算符在'{     “ collectio ...')

  $.ajax({}).always(function (data) {  
        var options = $('#example').attr('options');  
        var substr = JSON.stringify(data, null, 4);  
//-----------loop part------------  
        $.each((substr), function(i, val1) {
            $.each(val1.customerNumber, function(a, val3) {  
                var CustInfo = val1[a]["name"] + " " + val1[a]["email"];  
                options[options.length] = new Option(CustInfo, val1[a]["customerNumber"]);  
            });  
        });  
    });  

我只对“ collection”中的值感兴趣,我想要一个带有客户信息的选择框。像这样:

<select>
    <option value="1">Tester Test jo+billing@test.com</option>
    <option value="2">Demo Name</option>
</select>

1 个答案:

答案 0 :(得分:1)

首先,您不必使用JSON.stringify()即可将响应对象data转换为无法遍历属性的字符串。

  

我只对“收藏”中的值感兴趣。

然后不需要两个循环,只需使用data.collection即可:

$.ajax({}).always(function (data) {  
    var options = $('#example').attr('options');

    $.each((data.collection), function(i, obj) {
        var CustInfo = obj["name"] + " " + obj["email"];  
        options[options.length] = new Option(CustInfo, obj["customerNumber"]);
    });  
});  

data = {
  "collection": [{
    "customerNumber": 1,
    "email": "jo+billing@test.com",
    "name": "Tester Test"
  }, {
    "customerNumber": 2,
    "name": "Demo Name"
  }],
  "metaData": [],
  "pagination": [],
  "self": "some url"
};

$.each((data.collection), function(i, val1) {
  var CustInfo = val1["name"] + " " + val1["email"];
  console.log(CustInfo, val1["customerNumber"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>