2

I have a dynamic list and to get each object from each row and convert it into an JSON object that contains an array. I'm not sure the best approach on how to do this? any examples would be great.

<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 Answer 1

2

It would make more sense to have the output as an array of objects, instead of an object with properties containing arrays. With that in mind, you can use map() to achieve it:

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);
<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>

Note that I used the :eq() selector to retrieve the values from the input elements. It would be better to put classes on those elements to make selection easier and the code less brittle.

You should also fix your HTML as you're missing a couple of </div> tags.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.