"Merging" objects is different than putting objects into an array, which is an aggregation. Although it provides you with a single object to pass around, this aggregate is structurally different than a merged object. Aggregating adds a level of depth when accessing values in the new container, which is an array. This is different from merging which results in the same container, an object.
If you're using Dojo, than you can just do:
var mergedObject = dojo.mixin(object1, object2);
Otherwise, here's a simple way of merging two or more objects:
var merge = function() {
var result = {},
length = arguments.length,
object = null,
key = null;
if ( length < 2 ) {
throw "Must merge two or more objects";
}
for ( var i=0; i<length; ++i ) {
object = arguments[i];
for ( var key in object ) {
if ( !object.hasOwnProperty(key) ) { continue; }
result[key] = object[key];
}
}
return result;
};
var mergedObject = merge({a:1}, {b:2, c:3, d: {a: 1}}, {a: 2, c:[1,2,3]});
// mergedObject looks like {a:4, b:2, c:[1,2,3], d:{a:1}}
As you'll see, this is very different than an aggregation:
var aggregate = function() {
if ( length < 2 ) {
throw "Must aggregate two or more objects";
}
// The following can be simplified to
// return Array.prototype.slice.call(arguments);
// but is left in a more explicit manner to illustrate the difference
var result = [],
length = arguments.length;
for ( var i=0; i<length; ++i ) {
if ( arguments.hasOwnProperty(i) ) {
result.push(arguments[i]);
}
}
return result;
};
var aggregation = aggregate({a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]});
// aggregation looks like [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}];
So the difference is that mergedObject
looks like {a:4, b:2, c:[1,2,3], d:{a:1}}
, where property d
is accessed as mergedObject.d
, as opposed to aggregation
, which looks like [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}]
and where property d
is accessed as aggregation[1].d
.
It should also be noted that an explicit function for aggregation isn't necessary thanks to the literal array definition syntax available in JavaScript
var aggregation = aggregate({a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]});
is equivalent to
var aggregation = [{a:1}, {b:2, c:3, d: {a: 1}}, {a: 4, c:[1,2,3]}];