Skip to content

Instantly share code, notes, and snippets.

@KylePDavis
Created November 12, 2012 15:20
Show Gist options
  • Save KylePDavis/4059931 to your computer and use it in GitHub Desktop.
Save KylePDavis/4059931 to your computer and use it in GitHub Desktop.
Experimenting with the idea of copying Object slices and creating composite Objects via slices
var util = require("util");
var o = {
p1: {
c1:[{l1:"a"}, {l2:"b"}],
c2:{l3:3, l4:4}
},
p2: {foo:"bar"}
};
process.stdout.write("// Original object:\n");
process.stdout.write(util.inspect(o,false,10,true) + "\n\n");
function copyAtPath(src, path, dst) {
var srcNode = src,
dstNode = dst;
for (var i = 0, l = path.length - 1; i < l; ++i) {
var key = path[i];
if (!dstNode.hasOwnProperty(key))
dstNode[key] = srcNode[key] instanceof Array ? new Array(srcNode[key].length) : {};
srcNode = srcNode[key];
dstNode = dstNode[key];
}
dstNode[path[i]] = srcNode[path[i]];
dstNode[path[i]] = srcNode[path[i]];
}
var o2 = {};
["p1.c1.1", "p1.c1.0", "p1.c2", "p2"].forEach(function(path){
copyAtPath(o, path.split("."), o2);
process.stdout.write("// Copy after copyAtPath(" + JSON.stringify(path) + "):\n");
process.stdout.write(util.inspect(o,false,10,true) + "\n\n");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment