Created — forked from 140bytes/LICENSE.txt

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Object merge

View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12 13
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.
View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12
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
)
}
View LICENSE.txt
1
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])}
View LICENSE.txt
1 2 3 4 5 6 7 8 9
{
"name": "merge",
"description": "merge objects",
"keywords": [
"merge",
"objects",
"together"
]
}
View LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
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 commented

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.

Owner
jed commented

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.

Owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.