DEV Community

Keff
Keff

Posted on

5

Clean Object by Values

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay