Skip to content

Commit

Permalink
Adding flatten objects
Browse files Browse the repository at this point in the history
  • Loading branch information
kamaal111 committed May 20, 2024
1 parent b2bcd88 commit 0985473
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/objects/flatten.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import flatten from './flatten';

describe('flatten', () => {
it('flattens the given object', () => {
const nestedObject = {
hello: {
yes: 'true',
},
flat: 'yes',
nested: {
array: [1, 2],
},
};

const result = flatten(nestedObject);

expect(result).toEqual({
'hello.yes': 'true',
flat: 'yes',
'nested.array': [1, 2],
});
});
});
24 changes: 24 additions & 0 deletions src/objects/flatten.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function _flatten<Result extends object>(
obj: Record<string, unknown>,
recursiveContext?: { parentKey: string; result: Result }
): Result {
const initialResult = recursiveContext?.result ?? ({} as unknown as Result);
const parentKey = recursiveContext?.parentKey;

return Object.entries(obj).reduce<Result>((acc, [key, value]) => {
const newKey = parentKey != null ? `${parentKey}.${key}` : key;
if (typeof value !== 'object') return { ...acc, [newKey]: value };
if (Array.isArray(value)) return { ...acc, [newKey]: value };

return _flatten(value as Record<string, unknown>, {
parentKey: newKey,
result: acc,
});
}, initialResult);
}

function flatten<Result extends object>(obj: Record<string, unknown>): Result {
return _flatten(obj);
}

export default flatten;
1 change: 1 addition & 0 deletions src/objects/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './omit';
export * from './omitBy';
export * from './flatten';

0 comments on commit 0985473

Please sign in to comment.