FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Squash Object

20mins

Implement a function squashObject(obj) that flattens a deeply nested object into a single level.
The new object's keys are formed by joining nested keys with a period (.).

Rules:

  • If a property value is an object or array, flatten it recursively.
  • Null and undefined values must still be included.
  • Arrays should use their index as part of the key.
  • Empty keys ("") should be skipped (treated as if that layer does not exist).

Examples

const object1 = { a: 5, b: 6, c: { f: 9, g: { m: 17, n: 3, }, }, }; squashObject(object1); // { a: 5, b: 6, 'c.f': 9, 'c.g.m': 17, 'c.g.n': 3 } const object2 = { a: { b: null, c: undefined } }; squashObject(object2); // { 'a.b': null, 'a.c': undefined } const object3 = { a: { b: [1, 2, 3], c: ['foo'] } }; squashObject(object3); // { 'a.b.0': 1, 'a.b.1': 2, 'a.b.2': 3, 'a.c.0': 'foo' } const object4 = { foo: { '': { '': 1, bar: 2 }, }, }; squashObject(object4); // { foo: 1, 'foo.bar': 2 }

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests