merge-change
Version:
Advanced library for deep merging, patching, and immutable updates of data structures. Features declarative operations for specific merging behaviors, property management, custom type merging rules, and difference tracking. Supports complex data transform
34 lines • 1.34 kB
JavaScript
import { type } from '../type';
import { hasMethod } from '../has-method';
/**
* Converting a nested structure to a flat one
* Property names are transformed into a path {a: {b: 0}} => {'a.b': 0}
* @param value {object|*} Source objects for conversion
* @param separator
* @param [path] {string} Base path for forming keys of the flat object. Used for recursion.
* @param [clearUndefined] {boolean} Flag indicating whether to add undefined values to the result
* @param [result] {object} Result - flat object. Passed by reference for recursion
* @returns {{}}
*/
export function flat(value, separator = '.', clearUndefined = false, path = '', result = {}) {
if (hasMethod(value, 'toJSON'))
value = value.toJSON();
if (type(value) === 'object') {
const valueObject = value;
for (const [key, item] of Object.entries(valueObject)) {
flat(item, separator, clearUndefined, path ? `${path}${separator}${key}` : key, result);
}
}
else if (!clearUndefined || typeof value !== 'undefined') {
if (path === '') {
result = value;
}
else {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
result[path] = value;
}
}
return result;
}
//# sourceMappingURL=index.js.map