Remove extraneous properties from JavaScript objects

JavaScript objects can have numerous levels of properties that are set to null and posting them through fetch requests can lead to strange behavior if you are not checking for nulls. Why not clear out those fields?

Function

  • Take the current object and check if is is coalesced loosely to null with the == non strict equality evaluator
  • Use the reduce mapping over the entries to return the simplified object
function removeNullAndUndefined(inputObject) {
    return Object.entries(inputObject).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {});
}

Example

const z = {
  prop1: 1,
  prop2: null,
  prop3: undefined
};

console.table(removeNullAndUndefined(z));
(index) Value
prop1 1

Example for conditional header submission

In the following using the null entries of the missing properties from the args object to conditionally send headers for a fetch POST request

export async function POST(args, errorHandlerFn, requestFailedFn) {

    let headersToSend = removeNullAndUndefined({
        "Content-Type": args?.contentType || "application/json",
        "x-csrf-jwt": args?.csrf || null,
        "x-token": args?.token || null,
        "client-info": args?.clientInfo || null,
        "x-page-id": args?.pageId || null
    });

    console.log(`Request url: ${args.url}`);
    return await GeneralRequestHandler(async () => {
        return await fetch(args?.url, {
            method: "POST",
            cache: "no-store",
            body: JSON.stringify(args?.data),
            credentials: "include",
            headers: headersToSend
        });
    }, errorHandlerFn, requestFailedFn);
}