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:
"") 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 }
JavaScript Function
No test results yet
Click "Run" to execute tests