遍历json对象的所有元素

时间:2019-03-05 12:45:19

标签: javascript jquery

我有一个ajax调用,成功获取以下格式的json对象:

{test 1: Array(2), test 2: Array(3), test 3: Array(2)}

每个键内的数组看起来像

0: {IdProduct: "1", ProductName: "p1", ProductCode: "pc1", ProductVersion: "pv1"}
1: {IdProduct: "2", ProductName: "p2", ProductCode: "pc2", ProductVersion: "pv2"}

我想遍历所有这些元素以创建一个选项组 我的理解是要有两个for循环,并在第二个循环的第一个循环中创建级别nd选项,我编写了下面的代码,效果不佳:

    success: function(response) {
                    var options = '<optgroup label="'+Object.keys(response)[0]+'">';
                    response.forEach(function (data) {
                        options += '<option value="' + data.IdProduct + '">' + data.ProductName;
                        options += '</option>';
                    });
 options += '</optgroup>';
                    productsFilter.html(options);
                }

1 个答案:

答案 0 :(得分:0)

您确实需要两个循环来执行此操作。我做了一个for-in来遍历顶级JSON属性,然后将您的foreach用于数组。顺便说一下,我模拟了JSON响应只是为了填充其余部分。

var response = {
  'test 1': [{
    IdProduct: "1", 
    ProductName: "p1", 
    ProductCode: "pc1", 
    ProductVersion: "pv1"
  },{
    IdProduct: "2", 
    ProductName: "p2", 
    ProductCode: "pc2", 
    ProductVersion: "pv2"
  }], 
  'test 2': [{
    IdProduct: "3", 
    ProductName: "p3", 
    ProductCode: "pc3", 
    ProductVersion: "pv3"
  },{
    IdProduct: "4", 
    ProductName: "p4", 
    ProductCode: "pc4", 
    ProductVersion: "pv4"
  },{
    IdProduct: "5", 
    ProductName: "p5", 
    ProductCode: "pc5", 
    ProductVersion: "pv5"
  }], 
  'test 3': [{
    IdProduct: "6", 
    ProductName: "p6", 
    ProductCode: "pc6", 
    ProductVersion: "pv6"
  },{
    IdProduct: "7", 
    ProductName: "p7", 
    ProductCode: "pc7", 
    ProductVersion: "pv7"
  }]};

var options = "";
for (var key in response) {  
  options += '<optgroup label="'+ key + '">';
  response[key].forEach(function (data) {
    options += '<option value="' + data.IdProduct + '">' + data.ProductName;
    options += '</option>';
  });
  options += '</optgroup>';
}

var productsFilter = $("select#productsFilter");
productsFilter.html(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select id="productsFilter"></select>