UNPKG

es-next-tools

Version:

A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.

23 lines (22 loc) 763 B
/** * Flattens a nested object structure. * @param {T} obj - The object to flatten. * @param {string} [prefix=''] - The prefix to use for flattened keys. * @returns A flattened version of the input object. * @example * const nestedObj = { a: 1, b: { c: 2, d: { e: 3 } } }; * const flattenedObj = flatten(nestedObj); * // { 'a': 1, 'b.c': 2, 'b.d.e': 3 } */ export function flatten(obj, prefix = '') { return Object.keys(obj).reduce((acc, k) => { const pre = prefix.length ? prefix + '.' : ''; if (typeof obj[k] === 'object' && obj[k] !== null && !Array.isArray(obj[k])) { Object.assign(acc, flatten(obj[k], pre + k)); } else { acc[pre + k] = obj[k]; } return acc; }, {}); }