UNPKG

@tmlmobilidade/utils

Version:

A collection of utility functions and helpers for the TML Mobilidade Go monorepo, providing common functionality for batching operations, caching, HTTP requests, object manipulation, permissions, and more.

54 lines (53 loc) 1.63 kB
/** * Flattens an object using dot notation for nested fields. * Arrays are treated as leaf nodes and are not traversed. * Includes both nested objects and their individual properties as separate keys. * * Example: * flattenObject({ a: { b: 1, c: { d: 2 } } }) * -> { * 'a': { b: 1, c: { d: 2 } }, * 'a.b': 1, * 'a.c': { d: 2 }, * 'a.c.d': 2 * } */ export function flattenObject(input) { const result = {}; if (input === null || input === undefined) return result; const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value); const stack = [{ path: '', value: input }]; while (stack.length > 0) { const { path, value } = stack.pop(); if (!isObject(value)) { if (path) { result[path] = value; } continue; } const entries = Object.entries(value); if (entries.length === 0) { if (path) result[path] = value; continue; } // Add the current object itself to the result if (path) { result[path] = value; } for (const [key, child] of entries) { const nextPath = path ? `${path}.${key}` : key; if (Array.isArray(child)) { result[nextPath] = child; continue; } if (isObject(child)) { stack.push({ path: nextPath, value: child }); continue; } result[nextPath] = child; } } return result; }