Merging objects (associative arrays)

Viewed 102918

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 Answers

This is how Prototype does it:

Object.extend = function(destination, source) {
    for (var property in source) {
        if (source.hasOwnProperty(property)) {
            destination[property] = source[property];
        }
    }
    return destination;
};

called as, for example:

var arr1 = { robert: "bobby", john: "jack" };
var arr2 = { elizabeth: "liz", jennifer: "jen" };

var shortnames = Object.extend(arr1,arr2);

EDIT: added hasOwnProperty() check as correctly pointed out by bucabay in comments

In dojo, the 2-objects/arrays "merge" would be lang.mixin(destination, source) -- you can also mix multiple sources into one destination, etc -- see the mixin function's reference for details.

do you want to overwrite a property if the names are the same but the values are not?

And do you want to permanently change one of the original objects,

or do you want a new merged object returned?

function mergedObject(obj1, obj2, force){
    for(var p in obj1) this[p]= obj1[p];
    for(var p in obj2){
        if(obj2.hasOwnProperty(p)){
            if(force || this[p]=== undefined) this[p]= obj2[p];
            else{
                n= 2;
                while(this[p+n]!== undefined)++n;
                this[p+n]= obj2[p];
            }
        }
    }
}
  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

In 2019 you have 2 good options:

Object assigning [doc]

const result = Object.assign({}, baseObject, updatingObject);

Object spreading [doc]

const result = { ...baseObject, ...updatingObject};

The first one tends to be safer, more standard and polyvalent. A good pros and cons here

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);
Related