Skip to content

@3rd-Eden /LICENSE.txt forked from 140bytes/LICENSE.txt
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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
Owner
@jed

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
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.