Merge JSON Object with same “key” and add their “value” using JavaScript

后端 未结 5 1999
误落风尘
误落风尘 2021-02-06 19:07

My JSON looks like this

{\"rows\":[
    {\"key\":[\"zeit.de\"],\"value\":98},
    {\"key\":[\"google.com\"],\"value\":49},
    {\"key\":[\"spiegel.de\"],\"value\         


        
5条回答
  •  独厮守ぢ
    2021-02-06 19:35

    You can try something like this:

    var newData = {rows: []},
        index;
    
    for (var i = 0; i < data.rows.length;i++){
        index = newDataContains(data.rows[i].key);
        if (index == -1){
            newData.rows.push({key: data.rows[i].key, value: data.rows[i].value});
        } else {
            newData.rows[index].value += data.rows[i].value;
        }
    }
    
    function newDataContains(key){
        for (var i=0; i < newData.rows.length; i++){
            if (JSON.stringify(newData.rows[i].key) == JSON.stringify(key)) {
                return i;
                break;
            }
        }
        return -1;
    }
    

    jsfiddle: https://jsfiddle.net/9p81g5j6/

提交回复
热议问题