Clean Object by Values

Keff - Mar 24 '20 - - Dev Community

Function to remove specific values from an object (including nested values), by default only null values are removed, but an array of values to remove can be passed as second argument:

function cleanObject(obj, valueToClean = [null]) {
    if (!isObject(obj)) { // isObject defined below
        throw new Error('"obj" argument must be of type "object"');
    }

    const cleanObj = {};
    let filter = valueToClean;

    for (let key in obj) {
        const objValue = obj[key];

        if (Array.isArray(valueToClean)) {
            filter = val => valueToClean.includes(val);
        } else if (typeof valueToClean !== 'function') {
            filter = val => val === valueToClean;
        }

        if (isObject(objValue)) {
            cleanObj[key] = cleanObject(objValue, filter);
        } else if (!filter(objValue)) {
            cleanObj[key] = objValue;
        }
    }
    return cleanObj;
}
Enter fullscreen mode Exit fullscreen mode

isObject function from: Is value an object

function isObject(val){
  return (
    val != null && 
    typeof val === 'object' && 
    Array.isArray(val) === false
  );
}
Enter fullscreen mode Exit fullscreen mode

Usage:

const clean = cleanObject({ name: 'Manolo', email: null, tags: null });
// > { name: 'Manolo' }

const clean = cleanObject({ name: 'Manolo', email: null, tags: [] }, [null, []]);
// > { name: 'Manolo' }
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .