繁体   English   中英

我需要循环这个数组

[英]I need to loop this array

我使用 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: cannot use 'in' operator to search for 'length' 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"]);  
            });  
        });  
    });  

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

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

首先,您不必使用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>

暂无
暂无

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

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