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 to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs