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