Last active
August 29, 2015 14:18
-
-
Save YanivHaramati/d50273a554d27795c266 to your computer and use it in GitHub Desktop.
deepPick whitlisted nodes from an 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
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