Skip to content

Instantly share code, notes, and snippets.

@spikesagal
Last active November 3, 2015 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spikesagal/6f7822466887f19b9c65 to your computer and use it in GitHub Desktop.
Save spikesagal/6f7822466887f19b9c65 to your computer and use it in GitHub Desktop.
A safer way to mix JSON objects to be used as config or POST data.
function mixin() {
return JSON.parse('{'
+ [].reduce.call(arguments, function (prev, cur) {
var str = JSON.stringify(cur);
if (!str || str.slice(0, 1) !== '{' || str.slice(-1) !== '}') {
throw new Error('Invalid object: ' + str);
}
return (prev ? prev + ',' : '')
+ str.slice(1, -1);
}, null)
+ '}'
);
}
obj1 = {a:1, b:2};
obj2 = {b:3, c: 4, d: [1,2,3]}
console.log(mixin(obj1, obj2));
//console.log(mixin(obj1, obj2, [1,2,3]));
//console.log(mixin(obj1, obj2, function(){}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment