Skip to content

Commit

Permalink
fix(flattenObject): flatten for nested objects (#817)
Browse files Browse the repository at this point in the history
* fix(flattenObject): flatten for nested objects

* simplify logic

* style

---------

Co-authored-by: Sojin Park <[email protected]>
  • Loading branch information
nnnnoel and raon0211 authored Dec 1, 2024
1 parent 9a6a7db commit 7d9b11d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 13 additions & 0 deletions src/object/flattenObject.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,17 @@ describe('flattenObject', function () {
'a.2': 3,
});
});

it('handles object arrays', () => {
const result = flattenObject({
a: [1, { b: 2 }, 3, [{ c: 4 }]],
});

expect(result).toEqual({
'a.0': 1,
'a.1.b': 2,
'a.2': 3,
'a.3.0.c': 4,
});
});
});
4 changes: 1 addition & 3 deletions src/object/flattenObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ function flattenObjectImpl(object: object, prefix = ''): Record<string, any> {
}

if (Array.isArray(value)) {
for (let index = 0; index < value.length; index++) {
result[`${prefixedKey}.${index}`] = value[index];
}
Object.assign(result, flattenObjectImpl(value, prefixedKey));
continue;
}

Expand Down

0 comments on commit 7d9b11d

Please sign in to comment.