Group BY in JSON Array from HTML table

Bashar Al

I have this table and am trying to loop through the tr and get the IDs with data like this :

 var array = [];
    var res = $(".seq").map(function () {
        
        return {
            Id: $('.Id', this).val(),
            DR: $('.DR', this).val(),
            CR: $('.CR', this).val()
        };
    }).get();

    var json = JSON.stringify(res, null, 3);
    alert(json);
<table>
  <tr class="seq">
    <td>
      <select class="Id">
        <option value="1" selected="selected">row 1</option>
        <option value="2">row 2</option>
        <option value="3">row 3</option>
        <option value="4">row 4</option>
</select>
    </td>
     <td> 
       <input class="DR" value="10" type="text">
     </td>
    <td> 
       <input class="CR" value="10" type="text">
     </td>
  </tr>
  <tr class="seq">
    <td>
      <select class="Id">
        <option value="1" selected="selected">row 1</option>
        <option value="2">row 2</option>
        <option value="3">row 3</option>
        <option value="4">row 4</option>
</select>
    </td>
     <td> 
       <input class="DR" value="30" type="text">
     </td>
    <td> 
       <input class="CR" value="5" type="text">
     </td>
  </tr>
</table>

and the result is like this:

[
   {
      "Id": "1",
      "DR": "10",
      "CR": "10"
   },
   {
      "Id": "1",
      "DR": "30",
      "CR": "5"
   }
]

the question is how can i group BY ID if exists in the array , and if exist i want to add the values to CR and DR... to be like this :

  [
   {
      "Id": "1",
      "DR": "40",
      "CR": "15"
   }
]
undefined

You could filter the select elements that has the same value, and then iterate through the text inputs. The following snippet should work for many rows.

var array = [],
    ids = [],
    $select = $(".Id");

var res = $(".seq").map(function () {
    var id = $('.Id', this).val();

    if ($.inArray(id, ids) > -1) return;

    ids.push(id);
    var $m = $select.filter(function () {
        return this.value === id;
    });

    var DR = 0, CR = 0;

    $m.closest('td').siblings().find('.DR, .CR').each(function () {
        if ($(this).hasClass('DR')) DR += +this.value;
        else CR += +this.value;
    });

    return {
        Id: id,
        DR: DR,
        CR: CR
    };
}).get();

http://jsfiddle.net/syo26tcs/

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related