JSON 结果值作为 JavaScript/jQuery 中的键

JSON result value as key in JavaScript/jQuery

我有一个 JSON 结果,我想在其中创建手风琴菜单,我想要一个类似结果的值作为那些类似行的标题,请在下面查看我做了什么。

假设我有以下 JSON object

var items = [
    {label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
    {label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
    {label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
    {label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]

我的JS代码相关部分如下:

 var myUL = $("#accordion");
 myUL.empty();
 var currentName = "";    
 for (var i = 0; i <= items.length - 1; i++) {
      var label = items[i].label;
      if (items[i].name != currentName) {
            currentName = items[i].name;
                          list +=
                            '<a href="#demo' +
                            i +
                            '" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
                            currentName +
                            ' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
                          list += '<div class="collapse in" id="demo' + i + '">';
                        }
        
                        list += '<a href="#" class="list-group-item">' + label + "</a>";
                        
                      }
                      list += "</div>";
                      myUL.append(list);

我的一部分HTMLdiv

<div class="list-group panel" id="accordion"></div>

我现在得到的结果

我期待的

代码缩进在这种情况下会有所帮助。您的最后两行应该在循环内,这样代码才有意义。在每次迭代中,您必须关闭 div 并将代码添加到 myUL:

var items = [
    {label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
    {label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
    {label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
    {label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]


var myUL = $("#accordion");
myUL.empty();
var currentName = "";    
for (var i = 0; i <= items.length - 1; i++) {
  var label = items[i].label;
  var list = '';
  if (items[i].name != currentName) {
    currentName = items[i].name;
    list +=
        '<a href="#demo' +
        i +
        '" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
        currentName +
        ' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
    list += '<div class="collapse in" id="demo' + i + '">';
  }

  list += '<a href="#" class="list-group-item">' + label + "</a>";
  list += "</div>";
  myUL.append(list);
}
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-group panel" id="accordion"></div>

此外,您需要定义 list

我自己解决了这个问题,并将最终的源代码添加到这支笔中:

[https://codepen.io/rafihaidari/pen/ExyBGVK]