javascript - Group BY in JSON Array from HTML table -
i have table , trying loop through tr , ids info :
class="snippet-code-js lang-js prettyprint-override"> var array = []; var res = $(".seq").map(function () { homecoming { id: $('.id', this).val(), dr: $('.dr', this).val(), cr: $('.cr', this).val() }; }).get(); var json = json.stringify(res, null, 3); alert(json);
class="snippet-code-html lang-html prettyprint-override"><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 result this:
[ { "id": "1", "dr": "10", "cr": "10" }, { "id": "1", "dr": "30", "cr": "5" } ]
the question how can grouping id if exists in array , , if exist want add together values cr , dr... :
[ { "id": "1", "dr": "40", "cr": "15" } ]
you filter select
elements has same value, , iterate through text inputs. next snippet should work 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 () { homecoming 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; }); homecoming { id: id, dr: dr, cr: cr }; }).get();
http://jsfiddle.net/syo26tcs/
javascript jquery
No comments:
Post a Comment