Skip to content

Instantly share code, notes, and snippets.

@netojoaobatista
Created August 28, 2013 19:20
Show Gist options
  • Select an option

  • Save netojoaobatista/6370099 to your computer and use it in GitHub Desktop.

Select an option

Save netojoaobatista/6370099 to your computer and use it in GitHub Desktop.
Merge one or more objects
Object.merge = function() {
var al = arguments.length;
var result;
if (al < 2) {
throw new Error('U need at least 2 objects to merge');
}
result = arguments[0];
for (var i = 1; --al; ++i) {
var current = arguments[i];
Object.keys(current).map(function(key) {
result[key] = current[key];
});
}
return result;
};
{
"name": "karl",
"age": "25i",
"address": "long island",
"blood type": "AB",
"phones": [
{
"phoneNumer": "20103040",
"phoneType": "work"
},
{
"phoneNumer": "20103159",
"phoneType": "work"
},
{
"phoneNumer": "20133712",
"phoneType": "home"
}
],
"emails": [
{
"emailAdress": "[email protected]",
"phoneType": "personal"
},
{
"phoneNumer": "[email protected]",
"phoneType": "work"
}
]
}
var first = {"person":{"name":"karl","age":"25i","address":"long island","blood type":"AB"}};
var second = {
"phones": [
{"phoneNumer":"20103040","phoneType":"work"},
{"phoneNumer":"20103159","phoneType":"work"},
{"phoneNumer":"20133712","phoneType":"home"}
],
"emails": [
{"emailAdress":"[email protected]","phoneType":"personal"},
{"phoneNumer":"[email protected]","phoneType":"work"}
]
};
print(JSON.stringify(Object.merge(first.person, second)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment