javascript - Whitelist nested properties using this particular object format -
need "whitelist" object this:
{ a: { b: { c: '' } } }
apply to:
{ a: { b: { c: 1 } d: 2 e: 3 } }
result:
{ a: { b: { c: 1 } } }
any suggestions? not sure how implement using underscore. looking @ _.pick ran trouble nesting.
recursion array.prototype.reduce()
:
function getpaths(obj, whitelist) { return object.keys(whitelist) .reduce(function(whiteobj, key) { if (!obj.hasownproperty(key)) { } else if(typeof obj[key] === 'object') { whiteobj[key] = getpaths(obj[key], whitelist[key]); } else { whiteobj[key] = obj[key]; } return whiteobj; }, {}) } var whitelist = { a: { b: { c: '' } }, g: '' }; var obj = { a: { b: { c: 1 }, d: 2, e: 3 } }; var result = getpaths(obj, whitelist); console.log(result);
Comments
Post a Comment