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.
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.
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.
concat() can be used to merge multiple arrays together. But, it does not remove duplicates.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With