Merge array of javascript objects by property key

前端 未结 2 1580
天涯浪人
天涯浪人 2020-12-22 09:09

First of all: I already found this thread, which basically is exactly what I want, but I tried my best to apply it to my needs - I couldn\'t.

So, I have the followin

2条回答
  •  清酒与你
    2020-12-22 09:36

    Try this:

    function joinObjects( array ) {
    
        // Start with empty array
        var ret = new Array();
    
        // Iterate array
        for ( var i = 0; i < array.length; i++ ) {
    
            // Search by fieldname
            var match = false;
            var j;
            for ( j = 0; j < ret.length; j++ ) {
                if ( array[i].Fieldname == ret[j].Fieldname ) { match = true; break; }
            }
    
            // If not exists
            if ( !match ) {
    
                // Intert object
                ret.push({
                    Fieldname: array[i].Fieldname,
                    Value: new Array()
                });
    
            }
    
            // Insert value
            ret[j].Value.push( array[i].Value );
    
        }
    
        // Return new array
        return ret;
    
    }
    

    http://jsfiddle.net/6entfv4x/

提交回复
热议问题