Skip to content

Commit

Permalink
fix: support arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikaple committed Oct 11, 2023
1 parent 83705dc commit 41932ed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
27 changes: 27 additions & 0 deletions src/flatten.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,33 @@ describe('flattenObject', () => {
);
});

it('should handle arrays', () => {
testFlatten(
[
1,
{
a: {
b: {
c: 123,
},
d: [
{
e: { f: 456 },
},
],
},
'a.b.c': 789,
},
],
{
'[0]': 1,
'[1].a.b.c': 123,
'[1].a.d[0].e.f': 456,
'[1]["a.b.c"]': 789,
},
);
});

it('should handle complex arrays', () => {
testFlatten(
{ a: [0, { b: [1], c: { d: [2], 5: [6] } }] },
Expand Down
6 changes: 4 additions & 2 deletions src/flatten.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ export const flatten = <T>(
* flatten({ 'a["?"][0]': 1 }) // { a: { '?': [1] } }
*/
export const unflatten = (obj: any, options?: UniFlattenOptions) => {
const result = {};
const circularEntries: [string, any][] = [];
const normalEntries: [string, any][] = [];
Object.entries(obj).forEach(([key, value]) => {
Expand All @@ -107,7 +106,10 @@ export const unflatten = (obj: any, options?: UniFlattenOptions) => {
normalEntries.push([key, value]);
}
});
normalEntries.concat(circularEntries).forEach(([key, value]) => {

const entries = normalEntries.concat(circularEntries);
const result = /^\[\d+\]/.test(entries[0][0]) ? [] : {};
entries.forEach(([key, value]) => {
deepSet(result, key, value, options);
});
return result;
Expand Down

0 comments on commit 41932ed

Please sign in to comment.