Saltar al contenido

CódigoSin intentar

Aplanar un objeto anidado

Dificultad: media

{ user: { name: 'John', address: { city: 'NYC' } } } → { 'user.name': 'John', 'user.address.city': 'NYC' }.

  • los elementos de un array usan su índice: { tags: ['a'] } → { 'tags.0': 'a' }
  • null es un valor (ojo con typeof null === 'object'); las fechas también son valores
  • los objetos anidados vacíos no producen claves
Ver solución de referencia
export function flattenObject(obj: Record<string, unknown>, parentKey = ''): Record<string, unknown> {
let result: Record<string, unknown> = {};
for (const key in obj) {
const newKey = parentKey ? `${parentKey}.${key}` : key;
const value = obj[key];
// typeof null is 'object' too, and a Date is a value, not something to open up.
if (typeof value === 'object' && value !== null && !(value instanceof Date)) {
result = { ...result, ...flattenObject(value as Record<string, unknown>, newKey) };
} else {
result[newKey] = value;
}
}
return result;
}
Cargando editor…