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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more