Skip to content

CodeNot attempted

Flatten a nested object

Difficulty: medium

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

  • array items use their index: { tags: ['a'] } → { 'tags.0': 'a' }
  • null is a value (watch typeof null === 'object'); Dates are values too
  • empty nested objects produce no keys
Show reference solution
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;
}
Loading editor…