Merging objects (associative arrays)

前端 未结 16 1269
野的像风
野的像风 2020-12-04 08:20

What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for loop?

16条回答
  •  天涯浪人
    2020-12-04 08:47

    jquery has a boolean for deep copy. You could do something like that:

    MergeRecursive = function(arr1, arr2){
        $.extend(true, arr1, arr2);
        return arr1;                
    };
    

    Also you can edit this function to support n-arrays to merge.

    ArrayMergeRecursive = function(){
         if(arguments.length < 2){
              throw new Error("ArrayMergeRecursive: Please enter two or more objects to merge!");
         }
    
        var arr1=arguments[0];
        for(var i=0; i<=arguments.length; i++ ){
            $.extend(true, arr1, arguments[i]);                 
        }
    
        return arr1;                
    };
    

    So now you can do

    var arr1 = {'color': {'mycolor': 'red'}, 3: 5},
        arr2 = {4: 10, 'color': {'favorite': 'green', 0: 'blue'}},
        arr3 = ['Peter','Jhon','Demosthenes'],
        results = ArrayMergeRecursive(arr1, arr2, arr3); // (arr1, arr2 ... arrN)
    console.log("Result is:", results);
    

提交回复
热议问题