##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> |
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: