Home > Software engineering >  Return only the values that are not empty string or empty arrays from an object
Return only the values that are not empty string or empty arrays from an object

Time:10-12

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));
};

enter image description here

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!

CodePudding user response:

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.

CodePudding user response:

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));
};
  • Related