Here is a version that uses functional programming with map and reduce .
It recursively intersects both objects and deletes keys that are marked with an empty string on the object representing the deletes
function deleteKeys(deletions, obj) { if (deletions === "") { return null } return Object .keys(obj) .map(key => { if (!(key in deletions)) { // if the key is not in the object containing // the keys to delete return { [key]: obj[key] }; } //recursively create a filtered object const filteredObj = deleteKeys(deletions[key], obj[key]) // if that object is null, then return an empty object // else return the filtered object return filteredObj ? { [key]: filteredObj } : {} }) // we now have an array of object that we need to merge together :) .reduce((acc, obj) => Object.assign({}, acc, obj), {}) }
Here are the tests I ran to encode this:
const cleanedObj = deleteKeys( { first: "" }, { first: "", second: { hi: ["heelo"] }} ); console.log(cleanedObj); const cleanedObj2 = deleteKeys( { second: { hi: "" }}, { first: "", second: { hi: ["heelo"] }} ); console.log(cleanedObj2); const cleanedObj3 = deleteKeys( { second: "" }, { first: "", second: { hi: ["heelo"] }} ); console.log(cleanedObj3);
It is worth noting that this solution is a pure function ( https://en.wikipedia.org/wiki/Pure_function ), which means they will not change their original object, but instead will return a new one. No side effects of FTW
source share