Post này để nói về utils. Trong quá trình làm việc mình có rất nhiều hàm utils, nhưng mỗi 1 utils mình lại để ở 1 project khác nhau. Post này mình sẽ note lại các utils trong quá trình làm việc và để sau muốn dùng hoặc muốn custom thì nhìn lại cho dễ.
Utils
export const isEmpty = (obj) =>
[Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
export const removeEmpty = (obj) => {
return Object.keys(obj)
.filter((k) => obj[k] !== undefined && obj[k] !== null && obj[k] !== "")
.reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
};
Custom cho con với array
const removeEmpty = (obj) => {
return Object.keys(obj)
.filter((k) => {
const value = obj[k];
// check if value is an array
if (Array.isArray(value)) {
// Lọc các phần tử khác null, rỗng, undefined
obj[k] = value.filter((item) => item !== null && item !== "" && item !== undefined);
// check if array is not empty
return obj[k].length > 0;
}
// check it's not null, undefined, or an empty string
return value !== undefined && value !== null && value !== "";
})
.reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
};
export const checkObjectValueEmpty = (obj) => {
return Object.keys(obj).some((k) => obj[k] === undefined && obj[k] === null && obj[k] === "");
};
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export const isEmptyArray = (arr) => !(Array.isArray(arr) && arr?.length);