DEV Community

loading...

Clean Object by Values

nombrekeff profile image Manolo Edge ・1 min read

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;
}

isObject function from: Is value an object

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

Usage:

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

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

Discussion

pic
Editor guide