Merging objects (associative arrays)

前端 未结 16 1216
野的像风
野的像风 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:44

    Recursive solution (extends also arrays of objects) + null checked

    var addProps = function (original, props) {
        if(!props) {
            return original;
        }
        if (Array.isArray(original)) {
            original.map(function (e) {
                return addProps(e, props)
            });
            return original;
        }
        if (!original) {
            original = {};
        }
        for (var property in props) {
            if (props.hasOwnProperty(property)) {
                original[property] = props[property];
            }
        }
        return original;
    };
    

    Tests

    console.log(addProps([{a: 2}, {z: 'ciao'}], {timestamp: 13}));
    console.log(addProps({single: true}, {timestamp: 13}));
    console.log(addProps({}, {timestamp: 13}));
    console.log(addProps(null, {timestamp: 13}));
    
    [ { a: 2, timestamp: 13 }, { z: 'ciao', timestamp: 13 } ]
    { single: true, timestamp: 13 }
    { timestamp: 13 }
    { timestamp: 13 }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-04 08:47

    Here is the best solution.

    obj1.unshift.apply( obj1, obj2 );
    

    Also, obj1 can grow inside a loop without any problem. (lets say obj2 is dynamic)

    0 讨论(0)
  • 2020-12-04 08:52

    Yahoo UI (YUI) also has a helper function for this:

    http://developer.yahoo.com/yui/examples/yahoo/yahoo_merge.html

    YAHOO.namespace('example');
    
    YAHOO.example.set1 = { foo : "foo" };
    YAHOO.example.set2 = { foo : "BAR", bar : "bar" };
    YAHOO.example.set3 = { foo : "FOO", baz : "BAZ" };
    
    var Ye = YAHOO.example;
    
    var merged = YAHOO.lang.merge(Ye.set1, Ye.set2, Ye.set3);
    
    0 讨论(0)
  • 2020-12-04 08:53
    1. In Javascript there is no notion of associative array, there are objects
    2. The only way to merge two objects is to loop for their properties and copy pointers to their values that are not primitive types and values for primitive types to another instance
    0 讨论(0)
  • 2020-12-04 08:56

    Keep it simple...

    function mergeArray(array1,array2) {
      for(item in array1) {
        array2[item] = array1[item];
      }
      return array2;
    }
    
    0 讨论(0)
提交回复
热议问题