Last active
August 29, 2015 14:06
-
-
Save jasdeepkhalsa/57ec7641d1b3646ccab9 to your computer and use it in GitHub Desktop.
Copy or merge a JavaScript object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
obj = {'a':'b'}; | |
obj2 = {'x':'y'}; | |
var copy = JSON.parse(JSON.stringify(obj)); // Really fast! - copies original obj | |
copy['c'] = 'd'; | |
console.log(obj); // Outputs: {'a':'b'} | |
console.log(copy); // Outputs: {'a':'b', 'c':'d'} | |
var merge = $.extend(true, obj, obj2); // Uses jQuery - changes original obj | |
console.log(obj); // Outputs: {'a':'b', 'x':'y'} | |
console.log(merge); // Outputs: {'a':'b', 'x':'y'} | |
// Use $.clone for DOM objects, this is just for JavaScript objects! | |
function merge() { | |
var dst = arguments[0], | |
src, p, args = [].splice.call(arguments, 0); | |
while (args.length > 0) { | |
src = args.splice(0, 1)[0]; | |
if (toString.call(src) == '[object Object]') { | |
for (p in src) { | |
if (src.hasOwnProperty(p)) { | |
if (toString.call(src[p]) == '[object Object]') { | |
dst[p] = merge(dst[p] || {}, src[p]); | |
} else { | |
dst[p] = src[p]; | |
} | |
} | |
} | |
} | |
} | |
return dst; | |
} | |
// Uses plain JavaScript and works like the jQuery API | |
// For further info see this jsbin here: http://jsbin.com/sapoli/4/edit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment