Removal of empty collections and nulls

There are API services that throw an error when you pass an empty collection or null for certain optional fields.

An example of request and response:

{
    "name": "John Doe",
    "dob": "1970-01-01",
    ...
    "address": {}
}

Notice that the collection "address" has empty data.

Custom IML function removing the empty collections and arrays:

function removeEmpty(input) {
 if (typeof input !== "object" || input === null) return undefined;
 return Object.entries(input).reduce((acc, [key, value]) => {
  if (Array.isArray(value)) {
    acc[key] = value.map(item => removeEmpty(item));
    return acc;
  }
  if (typeof value === "object" && value !== null && !(value instanceof Date)) {
    if (Object.keys(value).length === 0) return acc;
    acc[key] = removeEmpty(value);
    return acc;
  }
  if (value === null) return acc; // comment this line if you have to pass null values.
  acc[key] = value;
  return acc;
 }, {});
}

In the module:

{
    "body": "{{removeEmpty(parameters)}}"
}

The request and response will be changed into this:

{
    "name": "John Doe",
    "dob": "1970-01-01"
}

Notice that the collection "address" was not entered at the request.

Last updated