从动态列表创建JSON对象

时间:2016-09-06 13:54:15

标签: jquery json

我有一个动态列表并从每一行获取每个对象并将其转换为包含数组的JSON对象。 我不确定如何做到这一点的最佳方法?任何例子都会很棒。

<div id="clientList">
    <row id="row_ccf06bc6-75e5-6db5-e7ed-b3f08856fb61">
        <label class="col-lg-1 control-label">Name:</label>
        <div class="col-lg-2"><input type="text" id="ClientName_ccf06bc6-75e5-6db5-e7ed-b3f08856fb61">
            <input type="hidden" id="ClientId_ccf06bc6-75e5-6db5-e7ed-b3f08856fb61">
    </row>
    <row id="row_cb5dbc04-62cd-5a19-edf2-2526f7b2aa91">
        <label class="col-lg-1 control-label">Name:</label>
        <div class="col-lg-2"><input type="text" id="ClientName_cb5dbc04-62cd-5a19-edf2-2526f7b2aa91">
            <input type="hidden" id="ClientId_cb5dbc04-62cd-5a19-edf2-2526f7b2aa91">
    </row>
</div>
var Account = new object();
$.each(row_???
    Account.Clients ='[ClientId: ClientId_???, ClientName: ClientName_???]'
)

1 个答案:

答案 0 :(得分:2)

将输出作为对象数组而不是具有包含数组的属性的对象更有意义。考虑到这一点,您可以使用map()来实现它:

&#13;
&#13;
var arr = $('#clientList row').map(function() {
  var $row = $(this);
  return {
    ClientName: $row.find('input:eq(0)').val(),
    ClientId: $row.find('input:eq(1)').val()
  };
}).get();

console.log(arr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clientList">
  <row id="row_ccf06bc6-75e5-6db5-e7ed-b3f08856fb61">
    <label class="col-lg-1 control-label">Name:</label>
    <div class="col-lg-2">
      <input type="text" id="ClientName_ccf06bc6-75e5-6db5-e7ed-b3f08856fb61" value="Client 1 name" />
      <input type="hidden" id="ClientId_ccf06bc6-75e5-6db5-e7ed-b3f08856fb61"value="Client 1 id" />
    </div>
  </row>
  <row id="row_cb5dbc04-62cd-5a19-edf2-2526f7b2aa91">
    <label class="col-lg-1 control-label">Name:</label>
    <div class="col-lg-2">
      <input type="text" id="ClientName_cb5dbc04-62cd-5a19-edf2-2526f7b2aa91" value="Client 2 name" />
      <input type="hidden" id="ClientId_cb5dbc04-62cd-5a19-edf2-2526f7b2aa91" value="Client 2 id"/>
    </div>
  </row>
</div>
&#13;
&#13;
&#13;

请注意,我使用:eq()选择器从input元素中检索值。最好将类放在这些元素上,以使选择更容易,代码也不那么脆弱。

您还应修复HTML,因为您错过了几个</div>代码。