Flatten Nested Object in JavaScript

Level 5433 keystrokes

flattenObject turns nested properties into top-level keys in dot notation; arrays are kept as they are.

JavaScript code

// Recursive function to flatten nested objects
1function flattenObject(obj, prefix = "") {
// Use reduce to build the flattened object
2 return Object.keys(obj).reduce((acc, key) => {
// Build the new key with dot notation
3 const newKey = prefix ? `${prefix}.${key}` : key;
// If the value is a plain object (not null, not an array), recurse with the new prefix
4 if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
// Merge the flattened child keys into the accumulator
5 Object.assign(acc, flattenObject(obj[key], newKey));
6 } else {
// Otherwise, assign the value directly
7 acc[newKey] = obj[key];
8 }
9 return acc;
10 }, {});
11}
12
// Test with nested object
13const nested = { a: 1, b: { c: 2, d: { e: 3 } }, f: [4, 5] };
// Result: { a: 1, "b.c": 2, "b.d.e": 3, f: [4, 5] }
14console.log(flattenObject(nested));

Output

{ a: 1, 'b.c': 2, 'b.d.e': 3, f: [ 4, 5 ] }
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 10
  • )× 10
  • {× 10
  • }× 10
  • =× 10
  • ,× 9
  • ;× 7
  • :× 7
  • [× 7
  • ]× 7

More JavaScript examples at level 5

← JavaScript typing practice