Last active
September 22, 2022 07:21
-
-
Save Mazuh/8209a608a655f91b9de319872d7a660a to your computer and use it in GitHub Desktop.
Remove all empty objects and undefined values from a nested object -- an enhanced and vanilla version of Lodash's `compact`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function compactObject(data) { | |
if (typeof data !== 'object') { | |
return data; | |
} | |
return Object.keys(data).reduce(function(accumulator, key) { | |
const isObject = typeof data[key] === 'object'; | |
const value = isObject ? compactObject(data[key]) : data[key]; | |
const isEmptyObject = isObject && !Object.keys(value).length; | |
if (value === undefined || isEmptyObject) { | |
return accumulator; | |
} | |
return Object.assign(accumulator, {[key]: value}); | |
}, {}); | |
} |
this function changes type array to object:
['a', 'b'] => {0: 'a', 1: 'b'}
Inside the reduce, change the value variable from const to let then add another if statement
if (typeof data !== "object") {
return data;
}
return Object.keys(data).reduce(function (accumulator, key) {
const isObject = data[key] !== null && typeof data[key] === "object";
let value = isObject ? compactObject(data[key]) : data[key];
const isEmptyObject = isObject && !Object.keys(value).length;
if (value === undefined) { // || isEmptyObject
return accumulator;
}
if (Array.isArray(data[key])) {
value = Object.values(value);
}
return Object.assign(accumulator, { [key]: value });
}, {});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this function changes type array to object:
['a', 'b'] => {0: 'a', 1: 'b'}