@maddimathon/utility-typescript
Version:
TypeScript utilities (types, functions, classes) to use in various projects.
49 lines (48 loc) • 1.58 kB
JavaScript
/**
* @since 2.0.0-beta.2
*
* @packageDocumentation
*/
/*!
* @maddimathon/utility-typescript@2.0.0-beta.5
* @license MIT
*/
import { deleteUndefinedProps } from './deleteUndefinedProps.js';
import { objectFlatten } from './objectFlatten.js';
/**
* Returns a single-level object record with kebab/snake/etc. case keys based on
* nested object keys.
*
* @category Functions – Object
*
* @since 2.0.0-beta.2
*/
export async function objectFlattenAsync(objPromise, args = {}) {
return Promise.resolve(objPromise).then(async (obj) => {
// returns
if (typeof obj !== 'object' || !obj) {
return obj;
}
const {
// prefix,
separator = '-', suffix, key_addSuffix, key_validate_addPrefix, } = objectFlatten.parseArgs(args);
return Promise.all(Object.keys(obj).map(async (t_key) => {
const value = obj[t_key];
const key = key_validate_addPrefix(t_key);
// continues
if (typeof value === 'undefined') {
return [[key_addSuffix(key), value]];
}
// continues
if (typeof value !== 'object' || !value || Array.isArray(value)) {
return [[key_addSuffix(key), value]];
}
return objectFlattenAsync(value, deleteUndefinedProps({
...args,
prefix: String(key),
separator,
suffix,
})).then(subObj => Object.entries(subObj));
})).then(entries => Object.fromEntries(entries.flat()));
});
}