如何将相同的值收集到JSON对象中?

时间:2019-09-12 07:07:04

标签: jquery arrays json

我有以下格式的多个输入:

<input type='text' class='i_skema_qty' id='skema_1_bbg' value='1000' />
<input type='text' class='i_skema_qty' id='skema_1_acg' value='700' />
<input type='text' class='i_skema_qty' id='skema_2_bbg' value='1200' />
<input type='text' class='i_skema_qty' id='skema_3_bbg' value='1700' />
<input type='text' class='i_skema_qty' id='skema_2_acg' value='1540' />
<input type='text' class='i_skema_qty' id='skema_1_spm' value='900' />
<input type='text' class='i_skema_qty' id='skema_2_spm' value='300' />


//CONTAINER
<input type='text' class='i_grand_total' id='total_bbg' />
<input type='text' class='i_grand_total' id='total_acg' />
<input type='text' class='i_grand_total' id='total_spm' />

我将收集所有这些输入值并将它们分组为一个json对象。格式应为:

[{"unit_kerja": "bbg","total": "3900"},{"unit_kerja": "acg","total": "2240"},{"unit_kerja": "spm","total": "1200"}]
数组中的

unit_kerja基于输入是动态的。但是,它总是大于零。然后,应将数组插入与数组计数匹配的i_grand_total容器中。

这是我目前停留在此处的脚本:

var grand_total = 0;
    $('.i_skema_qty').each(function(i){
        var _this_ttl    = $(this);

        var total_item   = parseFloat( _this_ttl.val().replace(',', '') );

        var arr_uk_skema = _this_ttl.attr('id').split('_');
        var uk_skema     = arr_uk_skema[2];                

        grand_total      = grand_total + total_item;
        alert(uk_skema +":"+ grand_total);          
    });

1 个答案:

答案 0 :(得分:0)

我将简化为一个由unit_kerja索引的对象,其值是数组对象,例如{"unit_kerja": "bbg","total": "3900"}。遍历每个i_skema_qty,如果尚未在累加器中创建对象,则将其添加到total中。然后,获取对象的值以将其转换回数组,并映射以将total转换为字符串而不是数字:

const grouped = [...$('.i_skema_qty')]
  .reduce((a, input) => {
    const key = input.id.match(/[a-z]+$/)[0];
    if (!a[key]) {
      a[key] = { unit_kerja: key, total: 0 };
    }
    a[key].total += Number(input.value);
    return a;
  }, {});
const output = Object.values(grouped)
  .map(obj => ({ ...obj, total: String(obj.total) }));
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' class='i_skema_qty' id='skema_1_bbg' value='1000' />
<input type='text' class='i_skema_qty' id='skema_1_acg' value='700' />
<input type='text' class='i_skema_qty' id='skema_2_bbg' value='1200' />
<input type='text' class='i_skema_qty' id='skema_3_bbg' value='1700' />
<input type='text' class='i_skema_qty' id='skema_2_acg' value='1540' />
<input type='text' class='i_skema_qty' id='skema_1_spm' value='900' />
<input type='text' class='i_skema_qty' id='skema_2_spm' value='300' />