Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active December 18, 2015 08:20
Show Gist options
  • Save williammalo/5753601 to your computer and use it in GitHub Desktop.
Save williammalo/5753601 to your computer and use it in GitHub Desktop.

##Object Merger

Recurcively merges two objects.

merge(
  {foo:"foo"},
  {bar:{lol:"lol"}}
);
function f(a,b){
var c="constructor"
,o=Object
,i;
for(i in b)
a[i]= //set item in first array to...
(b[i][c]===o&&a[i]&&a[i][c]===o) //if both items are an object
?f(a[i],b[i]) //merge those
:b[i]; //else, set a[i] to b[i]
return a //return final object
}
function f(a,b){var c="constructor",o=Object,i;for(i in b)a[i]=(b[i][c]===o&&a[i]&&a[i][c]===o)?f(a[i],b[i]):b[i];return a}
{
"name": "mergeObjects",
"description": "Recurcively merges two objects.",
"keywords": [
"object",
"merge",
"extend",
"recursive"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>{foo:"foo",bar:{lol:"lol"}}</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var mergeObjects = function f(a,b){var c="constructor",o=Object,i;for(i in b)a[i]=(b[i][c]===o&&a[i]&&a[i][c]===o)?f(a[i],b[i]):b[i];return a};
document.getElementById( "ret" ).innerHTML = mergeObjects(
{foo:"foo"},
{bar:{lol:"lol"}}
);
</script>
@atk
Copy link

atk commented Jun 11, 2013

A smaller, yet somewhat dangerous (if one of them is actually a string that contains the result of "({})+''") method would be to use a lot of coercion and regExp to test if both properties are objects:

function f(a,b,i){for(i in b)a[i]=(/(\[.*?ct\])\1/.test(a[i]+b[i])?f(a[i],b[i]):b[i];return a}

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