首页 > 解决方案 > 使用Javascript动态循环遍历对象数组

问题描述

使用 Laravel 应用程序从前端获取数据并使用 Javascript 在前端动态填充。在前端,我划分为 2 个主要列(左列和右列)。在左列有一个链接,当将鼠标悬停在或单击相应的策略时,该链接会显示在右侧。

问题是发现很难迭代包含 Javascript 对象集合的策略数组并在表中动态显示它们。

当我使用下面的方法时,我在表体中得到[object Object]

来自后端的 asm 变量

"agency_sales": [
    {
        "id": "111",
        "policies": [
            {
                "name": "JOHN DOE 1",
                "sum_covered": "555000",
                "date": "2018-05-16 12:02:32"
            },
            {
                "name": "JOHN DOE 2",
                "sum_covered": "404000",
                "date": "2018-02-20 17:33:25"
            },
        ]
    }
    {
        "id": "222",
        "policies": [
            {
                "name": "JOHN DOE 1",
                "sum_covered": "555000",
                "date": "2018-05-16 12:02:32"
            },
            {
                "name": "JOHN DOE 2",
                "sum_covered": "404000",
                "date": "2018-02-20 17:33:25"
            },
        ]
    }
]

左列包含具有动态 ID 的链接

<div class="col-md-4">
@foreach($asm as $a)
     <a href="#demo{{$i}}" class="list-group-item list-group-item-primary dropdown-toggle" data-toggle="collapse" data-parent="#MainMenu" style="color: #868ba1;" id="{{ $a['id'] }}"> Agency Sales Managers ID : {{ $a['id'] }} </a>
@endforeach
</div>

包含我想动态填充的表的右列

<div class="col-md-8">
 <table class="table table-hover mg-b-0 tx-11" id="summary-table">
    <thead>
      <tr>
        <th>NAME</th>
        <th>SUM</th>
        <th>DATE</th>
      </tr>
    </thead>
      <tbody>
        <tr> <!-- Add policies dynamically via JS under respective thead columns--></tr> 
      </tbody>
</table>
</div>

JavaScript 代码

$( document ).ready(function() {
    var asmData = {!! json_encode($asm) !!};
});

$(document).on("mouseenter", "a", function() {

  //Make sure table is empty
  $('#summary-table tbody tr').html('');

  //Execute ASM
  var asmPolicies = '';
  //Fetch id of a tag in the DOM
  var asmId = $(this).attr('id');
  for(var i = 0; i < asmData.length; i++) {
      if(asmId == asmData[i]['id']) {
          for(var j = 0; j < asmData[i]['policies'].length; j++){
              asmPolicies += '<tr><td>' + asmData[i]['policies'][j] + '</td></tr>';
          }
      }

  }
  //append asmPolicies Html to the table
  $('#summary-table tbody tr').append(asmPolicies);
  //END ASM
});

标签: javascriptjquerylaravelobjectfor-loop

解决方案


几个问题 - 主要问题是

  • 错误的 JSON
  • 不解析对象
  • 将 trs 附加到 trs 而不是 tbody

注意链接上数据属性的使用

const asmData = [{
  "id": "111",
  "policies": [{
      "name": "JOHN DOE 1",
      "sum_covered": "555000",
      "date": "2018-05-16 12:02:32"
    },
    {
      "name": "JOHN DOE 2",
      "sum_covered": "404000",
      "date": "2018-02-20 17:33:25"
    }
  ]
}, {
  "id": "222",
  "policies": [{
      "name": "JOHN DOE 3",
      "sum_covered": "555000",
      "date": "2018-05-16 12:02:32"
    },
    {
      "name": "JOHN DOE 4",
      "sum_covered": "404000",
      "date": "2018-02-20 17:33:25"
    }
  ]
}]



$(document).on("mouseenter", "a", function() {
  var $tb = $('#summary-table tbody');
  //Make sure table is empty

  $tb.empty()

  var asmId = $(this).attr('data-id'),
    asmPolicies = "";
  for (var i = 0; i < asmData.length; i++) {
    if (asmId == asmData[i]['id']) {
      for (var j = 0; j < asmData[i]['policies'].length; j++) {
        var pol = asmData[i]['policies'][j];
        asmPolicies += '<tr><td>' + pol.name + '</td><td>' + pol.sum_covered + '</td><td>' + pol.date + '</td><td>' + '</td></tr>';
      }
    }
  }
  //append asmPolicies Html to the table
  $tb.append(asmPolicies);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-id="111">111</a> | <a href="#" data-id="222">222</a>

<div class="col-md-8">
  <table class="table table-hover mg-b-0 tx-11" id="summary-table">
    <thead>
      <tr>
        <th>NAME</th>
        <th>SUM</th>
        <th>DATE</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <!-- Add policies dynamically via JS under respective thead columns-->
      </tr>
    </tbody>
  </table>
</div>


推荐阅读