Created
August 28, 2013 19:20
-
-
Save netojoaobatista/6370099 to your computer and use it in GitHub Desktop.
Merge one or more objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "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" | |
| } | |
| ] | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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