|
121 | 121 | "snippets": [
|
122 | 122 | {
|
123 | 123 | "title": "Filter Object",
|
124 |
| - "description": "Filters out entries in an object where the value is falsy.", |
| 124 | + "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.", |
125 | 125 | "code": [
|
126 | 126 | "export const filterObject = (object = {}) =>",
|
127 | 127 | " Object.fromEntries(",
|
128 | 128 | " Object.entries(object)",
|
129 |
| - " .map(([key, value]) => value && [key, value])", |
130 |
| - " .filter((item) => item),", |
| 129 | + " .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))", |
131 | 130 | " );",
|
132 | 131 | "",
|
133 | 132 | "// Usage:",
|
134 |
| - "const obj = { a: 1, b: null, c: undefined, d: 4 };", |
135 |
| - "console.log(filterObject(obj)); // Output: { a: 1, d: 4 }" |
| 133 | + "const obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };", |
| 134 | + "console.log(filterObject(obj1)); // Output: { a: 1, d: 4 }", |
| 135 | + "", |
| 136 | + "const obj2 = { x: 0, y: false, z: 'Hello', w: [] };", |
| 137 | + "console.log(filterObject(obj2)); // Output: { z: 'Hello' }", |
| 138 | + "", |
| 139 | + "const obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };", |
| 140 | + "console.log(filterObject(obj3)); // Output: { name: 'John', address: { city: 'New York' } }", |
| 141 | + "", |
| 142 | + "const obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };", |
| 143 | + "console.log(filterObject(obj4)); // Output: { e: 'Valid' }" |
136 | 144 | ],
|
137 | 145 | "tags": ["javascript", "object", "filter", "utility"],
|
138 | 146 | "author": "realvishalrana"
|
|
0 commit comments