camote-utils
Version:
A comprehensive TypeScript utility library featuring advanced string and number formatting, data structures, and algorithms
60 lines (59 loc) • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.objectToQueryString = exports.removeEmptyKeysEntries = void 0;
exports.objectFilterByKeys = objectFilterByKeys;
const removeEmptyKeysEntries = (obj) => {
const shouldInclude = ([_, value]) => {
const hasValues = Array.isArray(value) ? value.length > 0 : value !== null && value !== undefined && value !== '';
return (hasValues || value === 0);
};
const transformValues = (value) => {
if (Array.isArray(value)) {
return value;
}
else if (typeof value === 'object' && value !== null) {
const nestedObj = (0, exports.removeEmptyKeysEntries)(value);
return Object.keys(nestedObj).length > 0 ? nestedObj : null;
}
return value;
};
return Object.fromEntries(Object.entries(obj)
.filter(shouldInclude)
.map(([key, value]) => [key, transformValues(value)])
.filter(([_, value]) => value !== null && value !== undefined));
};
exports.removeEmptyKeysEntries = removeEmptyKeysEntries;
const objectToQueryString = (obj) => {
if (Array.isArray(obj) && obj.length > 0) {
const isMatrix = obj.every(item => Array.isArray(item) && item.length == 2);
if (isMatrix) {
return new URLSearchParams(obj).toString();
}
const isFlatArray = obj.every(item => typeof item !== "object") && obj.length % 2 == 0;
if (isFlatArray) {
const newObj = obj.reduce((acc, curr, idx, array) => {
if (idx % 2 == 0) {
acc[curr] = array[idx + 1];
}
return acc;
}, {});
return new URLSearchParams(newObj).toString();
}
throw new Error("Invalid array format: Expected either an array of key-value pairs (matrix) or a flat array with an even number of elements.");
}
if (typeof obj === "object" && obj !== null && Object.entries(obj).length > 0) {
return new URLSearchParams(obj).toString();
}
throw new Error("Invalid input format: Expected a non-empty object or a valid array format.");
};
exports.objectToQueryString = objectToQueryString;
// Function to filter a user object by dynamic keys
function objectFilterByKeys(data, keys) {
const filteredData = {};
keys.forEach(key => {
if (key in data) {
filteredData[key] = data[key];
}
});
return filteredData;
}