Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you combine two objects in Javascript? [duplicate]

Possible Duplicate:
How can I merge properties of two JavaScript objects dynamically?

If I have two Javascript objects which I am using as a list of key-value pairs:

var a = {a:1};
var b = {b:2};

what is the most efficient way to combine them into a third object which contains the properties of both?

var c = {a:1, b:2};

I don't mind if either or both of a and b are modified in the process.

like image 310
Armand Avatar asked Jun 22 '12 16:06

Armand


People also ask

How do I merge two objects in JavaScript?

To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.

How do you combine properties of two objects?

In the above example, two objects are merged into one using the Object. assign() method. The Object. assign() method returns an object by copying the values of all enumerable properties from one or more source objects.

Does concat remove duplicates JavaScript?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates.


1 Answers

You can do simply this :

   var c = {};
   for (var key in a) {
      c[key] = a[key];
   }
   for (var key in b) {
      c[key] = b[key];
   }

If you want to do a deep merging (assuming you don't want to copy the functions and prototypes), you can use this :

  function goclone(source) {
        if (Object.prototype.toString.call(source)==='[object Array]') {
            var clone = [];
            for (var i=0; i<source.length; i++) {
                if (source[i]) clone[i] = goclone(source[i]);
            }
            return clone;
        } else if (typeof(source)=="object") {
            var clone = {};
            for (var prop in source) {
                if (source[prop]) {
                    var firstChar = prop.charAt(0);
                    clone[prop] = goclone(source[prop]);
                }
            }
            return clone;
        } else {
            return source;
        }
    }


   var c = {};
   for (var key in a) {
      c[key] = goclone(a[key]);
   }
   for (var key in b) {
      c[key] = goclone(b[key]);
   }

But frankly I never saw the use for a deep merging in javascript...

like image 166
Denys Séguret Avatar answered Oct 07 '22 17:10

Denys Séguret