Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,17 @@ The following items will NOT be removed:

* Empty string, `''`
* Null, `null`

## Options

### `removeAllFalsy`

Optional boolean.
If provided, the empty string `''` and `null` will be removed as well.

```js
import removeUndefinedObjects from 'remove-undefined-objects';

console.log(removeUndefinedObjects({key1: null, key2: 123, key3: ''}), {removeAllFalsy: true});
// { key2: 123 }
```
39 changes: 26 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,43 @@
return typeof obj === 'object' && obj !== null && !Object.keys(obj).length;
}

export interface RemovalOptions {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having a default and secondary export in the same file gets really messy in CJS dist builds, causing types to get screwed up, do you mind either not exporting this or moving it to a separate file and exposing that in the exports config?

"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"./package.json": "./package.json"
},

We have a custom ESLint plugin that has the rule that's being flagged for this case below. There's some more details about why it can be problematic here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I removed the second export and filed readmeio/standards#919. Thanks for the tip!

removeAllFalsy?: boolean;
}

// Modified from here: https://stackoverflow.com/a/43781499
function stripEmptyObjects(obj: any) {
function stripEmptyObjects(obj: any, options: RemovalOptions = {}) {
const cleanObj = obj;

if (obj === null && options.removeAllFalsy) {
return undefined;
}

if (!isObject(obj) && !Array.isArray(cleanObj)) {
return cleanObj;
} else if (obj === null) {
return undefined;
}

if (!Array.isArray(cleanObj)) {
Object.keys(cleanObj).forEach(key => {
let value = cleanObj[key];

if (typeof value === 'object' && value !== null) {
value = stripEmptyObjects(value);
if (typeof value !== 'object') {
return;
}

if (isEmptyObject(value)) {
if (value === null) {
if (options.removeAllFalsy) {
delete cleanObj[key];
} else {
cleanObj[key] = value;
}
} else if (value === null) {
// Null properties in an object should remain!
return;
}

value = stripEmptyObjects(value, options);

if (isEmptyObject(value)) {
delete cleanObj[key];
} else {
cleanObj[key] = value;
}
});

Expand All @@ -39,7 +52,7 @@
cleanObj.forEach((o, idx) => {
let value = o;
if (typeof value === 'object' && value !== null) {
value = stripEmptyObjects(value);
value = stripEmptyObjects(value, options);

if (isEmptyObject(value)) {
delete cleanObj[idx];
Expand All @@ -57,7 +70,7 @@
return cleanObj.filter(el => el !== undefined);
}

export default function removeUndefinedObjects<T>(obj?: T): T | undefined {
export default function removeUndefinedObjects<T>(obj?: T, options?: RemovalOptions): T | undefined {

Check failure on line 73 in src/index.ts

View workflow job for this annotation

GitHub Actions / build (18)

In a dual package world you cannot ship a file for CJS environments that has a mix of `default` and named exports. This export should either be made a named export or refactor this file to have just one default export

Check failure on line 73 in src/index.ts

View workflow job for this annotation

GitHub Actions / build (20)

In a dual package world you cannot ship a file for CJS environments that has a mix of `default` and named exports. This export should either be made a named export or refactor this file to have just one default export
if (obj === undefined) {
return undefined;
}
Expand All @@ -68,7 +81,7 @@
let withoutUndefined = JSON.parse(JSON.stringify(obj));

// Then we recursively remove all empty objects and nullish arrays.
withoutUndefined = stripEmptyObjects(withoutUndefined);
withoutUndefined = stripEmptyObjects(withoutUndefined, options);

// If the only thing that's leftover is an empty object then return nothing.
if (isEmptyObject(withoutUndefined)) return undefined;
Expand Down
33 changes: 33 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ test('should leave primitives alone', () => {
expect(removeUndefinedObjects(undefined)).toBeUndefined();
});

test('should leave only truthy primitives alone when removeAllFalsy is true', () => {
expect(removeUndefinedObjects(1234, { removeAllFalsy: true })).toBe(1234);
expect(removeUndefinedObjects('1234', { removeAllFalsy: true })).toBe('1234');
expect(removeUndefinedObjects(null, { removeAllFalsy: true })).toBeUndefined();
expect(removeUndefinedObjects(undefined, { removeAllFalsy: true })).toBeUndefined();
});

test("should also remove '' and null values when removeAllFalsy is true", () => {
expect(removeUndefinedObjects({ value: 1234 }, { removeAllFalsy: true })).toStrictEqual({ value: 1234 });
expect(removeUndefinedObjects({ value: '1234' }, { removeAllFalsy: true })).toStrictEqual({ value: '1234' });
expect(removeUndefinedObjects({ value: null }, { removeAllFalsy: true })).toBeUndefined();
expect(removeUndefinedObjects({ value: undefined }, { removeAllFalsy: true })).toBeUndefined();
});

test('should remove empty objects with only empty properties', () => {
const obj = {
a: {
Expand Down Expand Up @@ -66,6 +80,25 @@ test('should remove empty arrays from within object', () => {
});
});

test('should remove empty arrays and falsy values from within object when removeAllFalsy is true', () => {
const obj = {
a: {
b: undefined,
c: {
d: undefined,
},
},
d: [1234, undefined],
e: [],
f: null,
g: [null, undefined, null],
};

expect(removeUndefinedObjects(obj, { removeAllFalsy: true })).toStrictEqual({
d: [1234],
});
});

test('should remove undefined and null values from arrays', () => {
expect(removeUndefinedObjects([undefined, undefined])).toBeUndefined();
expect(removeUndefinedObjects([null])).toBeUndefined();
Expand Down
Loading