need "whitelist" object to look like this:
{
a: {
b: {
c: ''
}
}
}
apply to:
{
a: {
b: {
c: 1
}
d: 2
e: 3
}
}
result:
{
a: {
b: {
c: 1
}
}
}
Any suggestions? Not sure how to implement this using underscore. Was looking at _.pick but ran into trouble with the nesting.
Recursion with 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);