Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Last active August 29, 2015 14:18
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 YanivHaramati/d50273a554d27795c266 to your computer and use it in GitHub Desktop.
Save YanivHaramati/d50273a554d27795c266 to your computer and use it in GitHub Desktop.
deepPick whitlisted nodes from an object
function getElement(obj, element) {
var res = {};
var nodes = element.split('.');
var currentSelf = res;
var currentObj = obj;
if (nodes.length === 1) {
res[element] = obj[element];
return res;
} else {
nodes.slice(0, nodes.length -1).forEach(function(key) {
currentSelf[key] = {};
currentSelf = currentSelf[key];
currentObj = currentObj[key];
});
var lastKey = nodes[nodes.length - 1];
currentSelf[lastKey] = currentObj[lastKey];
}
return res;
}
function merge(self) {
self = self || {};
var args = Array.prototype.slice.call(arguments, 1);
args.forEach(function(other) {
Object.keys(other).map(function(key) {
self[key] = other[key];
});
});
return self;
}
function deepPick(obj, whitelist) {
return whitelist.reduce(function(p, c) {
return merge(p, getElement(obj, c));
}, {});
}
// simple tests
var obj = {a:1, b:2,c:3,d:{e:4, f:{g:8, z:0}, h: [1,2,3], i: [{j:1}, {k:2}]}}
// Object {a: 1, b: 2, c: 3, d: Object}
var res = deepPick(obj, ["a", "d.i"])
// Object {a: 1, d: Object}
// should contain an array
res.d.i
// [Objectj: 1__proto__: Object, Object]
res = deepPick(obj, ["a", "d.f.g"])
//Object {a: 1, d: Object}
// shouldn't contain z
res.d.f
//Object {g: 8}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment