如何使用jquery在嵌套数组中显示数据?

时间:2018-11-21 07:19:42

标签: javascript jquery arrays json

我只想显示“ A”:值或“ B”:值或“ C”:值

赞:

选择divOne>选择underOne

A:x1

A:x2

但是这样显示:

A:x1

B:y1

C:z1

A:x2

B:y2

C:z2

怎么可能?

我尝试了键[“ A”]等。

jQuery和数组

$(document).ready(function() {
  var data = {
    "divOne": {
      "underOne": [{
          "A": "x1",
          "B": "y1",
          "C": "z1"
        },
        {
          "A": "x2",
          "B": "y2",
          "C": "z2"
        }

      ]
    },
    "divTwo": {
      "underThree": [{
          "A": "x5",
          "B": "y5",
          "C": "z5"
        },
        {
          "A": "x6",
          "B": "y6",
          "C": "z6"
        }
      ]
    }
  };

  var firstSelect = $('<select id="firstSelect"><option  >Select</option></select>').appendTo("#container");
  var secondSelect = $('<select id="secondSelect"> </select>').appendTo("#container");
  var results = $('<div id="results"> </div>').appendTo("#container");

  $.each(data, function(item, key) {
    firstSelect.append('<option >' + item + '</option>');
  });

  firstSelect.on("change", function(e) {
    secondSelect.empty().append("<option value='' >select</option>").change();
    var item;
    var selected = $(this).val();
    if (selected.length > 0) {
      item = data[selected];
      $.each(item, function(item, key) {
        secondSelect.append('<option >' + item + '</option>');
      });
    }
  });

  $("#secondSelect").on("change", function(e) {
    results.empty().append("<span></span>");
    var item1;
    var selected = $(this).val();
    if (selected.length > 0) {
      for (var i = 0; i < selected.length; i++) {
        item1 = data[firstSelect.val()][selected];
        $.each(item1[i], function(item, key) {
          results.append('<span >' + item + '</span>:');
          results.append('<span >' + key + '</span></br>');
        });
      }
    }
  });
});

0 个答案:

没有答案