Until now I have the following function:
export const useClearEmptyAttributes = (
obj: { [s: string]: unknown } | ArrayLike<unknown>,
) => {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v));
};
It eliminates an empty field "phone number" which was empty, but not socialLinks (which is an array).
How can I modify my function to eliminate empty arrays too, not just empty strings?
Thank you!
since you are targeting empty strings and empty arrays and both have length property you can check for the length if it is bigger than 0:
export const useClearEmptyAttributes = (
obj: { [s: string]: unknown } | ArrayLike<unknown>,
) => {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v.length > 0));
};
This would work if you want to add checking empty arrays plus your current check:
export const useClearEmptyAttributes = (
obj: { [s: string]: unknown } | ArrayLike<unknown>,
) => {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => Array.isArray(v)?v.length:v));
};
But if you want to check also for empty objects, etc it can be further modified.