Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@3rd-Eden
Forked from 140bytes/LICENSE.txt
Created May 24, 2011 10:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3rd-Eden/988478 to your computer and use it in GitHub Desktop.
Save 3rd-Eden/988478 to your computer and use it in GitHub Desktop.
Object merge
function m( // named function, for recursion / deeper nested objects
a // first object
,b // second
,c // placeholder
){
for(c in b) //loop
b.hasOwnProperty(c) && ( // must be own prop
(typeof a[c])[0]=='o' ? // if the type is an object.
m(a[c],b[c]) : // call the merge function on the object
a[c]=b[c] // or just override it
)
}
function m(a,b,c){for(c in b)b.hasOwnProperty(c)&&((typeof a[c])[0]=='o'?m(a[c],b[c]):a[c]=b[c])}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Arnout Kazemier <blog.3rd-Eden.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "merge",
"description": "merge objects",
"keywords": [
"merge",
"objects",
"together"
]
}
function m(a,b,c){for(c in b)b.hasOwnProperty(c)&&((typeof a[c])[0]=='o'?m(a[c],b[c]):a[c]=b[c])}
var FIRST = {
1:1
, 2:2
, "three":"three"
, "four": [1,2,3,4,5]
, "more":{
"five": 5
, "six": "six"
, "seven": [1,2,3,4,5,6,7]
}
};
var moar = {
1:2
, 2:3
, "three":"seven"
, "four": [4,5,7]
, "more":{
"five": 4
, "six": "hello world"
, "seven": "pewpew"
, "foo":"bar"
}
};
m(FIRST,moar);
console.log(FIRST);
@jed
Copy link

jed commented May 25, 2011

better compat in same number of bytes:

function m(a,b,c){for(c in b)if(b.hasOwnProperty(c))typeof a[c]=='object'?m(a[c],b[c]):a[c]=b[c]}

you still have a lot of room left. how about adding return a, and the ability to extend n objects? useful for creating a new object non-destructively.

@3rd-Eden
Copy link
Author

3rd-Eden commented May 25, 2011 via email

@jed
Copy link

jed commented May 25, 2011

that sounds expensive, but if you can pull it off...

i think returning a value and allowing m({}, objA, objB) would be the way to go, since folks expect that behavior.

@3rd-Eden
Copy link
Author

3rd-Eden commented May 25, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment