Skip to content

Instantly share code, notes, and snippets.

@woffleloffle
Last active August 29, 2015 14:06
Show Gist options
  • Save woffleloffle/552ce0cca1bb956b470c to your computer and use it in GitHub Desktop.
Save woffleloffle/552ce0cca1bb956b470c to your computer and use it in GitHub Desktop.
Merging two JS Objects into one
/**
* Merge two JS Objects
*
* returns a new Object with values of
* first and second added to each other.
*
* Note:
* Object items should only have integers for values
* ..otherwise, boom!
*/
var merge = function(first, second) {
first = first || {};
second = second || {};
var item,
// Clone the first object.
// We add the second's values to this.
third = JSON.parse(JSON.stringify(first));
// Loop through the object and add the values.
for (item in second) {
if (typeof second[item] === 'object') {
// Recurse
third[item] = merge(first[item], second[item]);
} else {
// remember: third is a clone of first.
third[item] = third[item] || 0;
third[item] += second[item];
}
}
return third;
};
/////// THINGS!
var x = {
x: 1,
y: 1,
foo: {
bar: 1
}
};
var y = {
x: 2,
y: 2,
foo: {
bar: 2
}
};
var z = {
x: 3,
y: 3,
foo: {
bar: 3
}
};
var things = [x, y, z];
var all = {};
// Reverse loop
for (var i = things.length - 1; i >= 0; i--) {
console.log(all);
all = merge(all, things[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment