Merge array of javascript objects by property key

前端 未结 2 1565
天涯浪人
天涯浪人 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/

    0 讨论(0)
  • 2020-12-22 09:52

    What you'd want to do first is build a hash with Fieldname as key, and an array as value. Then you'd want to use reduce to add the values into the hash and array. Then you can transform it into an array using Object.keys and map.

    var input = [
      {Name: 'M100', ObjectID: 1, ObjectType: 'TEC_MapLocation'},
      {Name: 'M200', ObjectID: 2, ObjectType: 'TEC_MapLocation'},
      {Name: 'FL456', ObjectID: 4, ObjectType: 'TEC_FunctionalLocation'},
      {Name: 'E0192', ObjectID: 5, ObjectType: 'TEC_Equipment'}
    ];
    
    var hash = input.reduce(function(carry, item){
      
      // Create the name
      var name = 'Übergeordnete ' + item.ObjectType;
    
      // If array with name doesn't exist, create it
      if(!carry[name]) carry[name] = [];
    
      // If item isn't in the array, add it.
      if(!~carry[name].indexOf(item.Name)) carry[name].push(item.Name);
    
      return carry;
    }, {});
    
    // Convert the hash into an array
    var output = Object.keys(hash).map(function(key, index, array){
      return { Fieldname: key, Value: hash[key] }
    });
    
    document.write(JSON.stringify(output));

    0 讨论(0)
提交回复
热议问题