How do I merge an array of objects in Javascript?

前端 未结 3 1697
我寻月下人不归
我寻月下人不归 2020-12-20 23:19

Example:

var array1 = [ {\'key\':1, \'property1\': \'x\'}, {\'key\':2, \'property1\': \'y\'} ]
var array2 = [ {\'key\':2, \'property2\': \'a\'}, {\'key\':1,          


        
3条回答
  •  萌比男神i
    2020-12-20 23:27

    You could do something like this:

    function merge(array1, array2) {
        var keyedResult = {};
    
        function _merge(element) {
            if(!keyedResult[element.key]) {
                keyedResult[element.key] = {};
            }
    
            var entry = keyedResult[element.key];
            for(var property in element) if(element.hasOwnProperty(property)) {
                if(property !== "key") {
                    entry[property] = element[property];
                }                
            }
    
            entry["key"] = element.key;
        }
    
        array1.forEach(_merge);
        array2.forEach(_merge);
    
        var result = [];
    
        for(var key in keyedResult) if(keyedResult.hasOwnProperty(key)) {
            result.push(keyedResult[key]);
        }
    
        return result.sort(function(a, b) {
            return a.key - b.key;
        });
    }
    

    You could eliminate the sort if you don't care about the order. Another option is to use an array instead of the map I have used (keyedResult) if you have numeric keys and don't care about the array being sparse (i.e., if the keys are non-consecutive numbers). Here the key would also be the index of the array.

    This solution also runs in O(n).

    fiddle

提交回复
热议问题