arrays - Javascript - Deep copy specific properties from one object to another new object -
suppose have source object can arbitrary javascript object, may have properties objects (or arrays or functions), nested level.
i want perform deep copy of object new target object. want copy specific white-listed properties. these @ level in source object.
up till i've been manually assigning white-listed properties in source object target object. doesn't seem elegant , nor reusable. can please give me guidance on implementing using more elegant , re-usable approach?
this should looking for, including circular references.
edit: keep in mind slower , slower objects lots of circular references inside! lookup see if reference has been seen simple scan.
var util = require('util') var propertiestocopy = { 'a' : true, 'b' : true, 'c' : true, 'd' : true, 'e' : true, 'f' : true, 'p1': true, 'p2': true, 'g' : true }; var obj; obj = { p2 : { : 1, b : 2, c : {}, d : { f : 2 } }, p3 : 'hello' }; // circular obj.p1 = obj; obj.p2.d.e = obj; // sub-circular obj.p2.g = obj.p2.c; function getnewobjectfromobjects(obj, objects) { (var = 0; < objects.length; i++) { if (obj === objects[i].old) return objects[i].new; } return false; } function whitelistedcopy(obj, whitelist, root, newroot, objects) { var cloned = {}; var keys = object.keys(obj); root = root || obj; newroot = newroot || cloned; objects = objects || [ {'old' : root, 'new': newroot} ]; keys.foreach(function(val) { if (whitelist[val] === true) { if (typeof(obj[val]) === typeof({}) || typeof(obj[val]) === typeof([]) ) { var reference = getnewobjectfromobjects(obj[val], objects); if (reference === false) { cloned[val] = whitelistedcopy(obj[val], whitelist, root, newroot, objects); objects.push({ 'old' : obj[val], 'new': cloned[val]}); } else { cloned[val] = reference; } } else { cloned[val] = obj[val]; } } }); return cloned; } var clonedobject = whitelistedcopy(obj, propertiestocopy); console.log(util.inspect(clonedobject)); console.log('assert c , g same reference:', clonedobject.p2.g === clonedobject.p2.c); console.log('assert p1 circular:', clonedobject === clonedobject.p1);
Comments
Post a Comment