| 1 |
/** |
| 2 |
* Compact object - remove empty nested objects and undefined values. |
| 3 |
* |
| 4 |
* @link https://gist.github.com/Mazuh/8209a608a655f91b9de319872d7a660a |
| 5 |
* |
| 6 |
* @param {Object} obj - object to work with. |
| 7 |
* |
| 8 |
* @return {Object} |
| 9 |
*/ |
| 10 |
export default function compactObject(obj) { |
| 11 |
if (typeof obj !== 'object') { |
| 12 |
return obj; |
| 13 |
} |
| 14 |
|
| 15 |
return Object.keys(obj).reduce((accumulator, key) => { |
| 16 |
const isObject = typeof obj[key] === 'object'; |
| 17 |
const value = isObject ? compactObject(obj[key]) : obj[key]; |
| 18 |
const isEmptyObject = isObject && !Object.keys(value).length; |
| 19 |
|
| 20 |
if (value === undefined || isEmptyObject) { |
| 21 |
return accumulator; |
| 22 |
} |
| 23 |
|
| 24 |
return Object.assign(accumulator, { [key]: value }); |
| 25 |
}, {}); |
| 26 |
} |
| 27 |
|