@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
31 lines (30 loc) • 1.18 kB
JavaScript
export default function flattenValues(values, ignoreKeys) {
const flattened = flattenValue(values, '', ignoreKeys);
return flattened;
}
function flattenValue(values, prefix = '', ignoreKeys) {
var _a;
const keys = Object.keys(values);
let flattened = {};
for (const key of keys) {
const value = values[key];
const isWildCardIgnored = (_a = ignoreKeys === null || ignoreKeys === void 0 ? void 0 : ignoreKeys.includes(`*.${key}`)) !== null && _a !== void 0 ? _a : false;
const dotKey = prefix && !isWildCardIgnored ? `${prefix}.${key}` : key;
if (shouldFlatten(value, ignoreKeys, key)) {
flattened = {
...flattened,
...flattenValue(value, dotKey, ignoreKeys),
};
}
else if (isWildCardIgnored) {
flattened[prefix] = { ...flattened[prefix], [key]: value };
}
else {
flattened[dotKey] = value;
}
}
return flattened;
}
function shouldFlatten(value, ignoreKeys, key) {
return value && typeof value === 'object' && !(ignoreKeys === null || ignoreKeys === void 0 ? void 0 : ignoreKeys.includes(key));
}