From 9a5170d322f1953dea9db017e0bfa43ae4f263da Mon Sep 17 00:00:00 2001 From: ytkimirti Date: Wed, 14 Oct 2026 19:06:14 +0300 Subject: [PATCH] fix: keep JSON arrays as arrays when sorting keys --- .../databrowser/hooks/sort-object.test.ts | 14 ++++++++++++++ .../databrowser/hooks/use-fetch-simple-key.tsx | 9 +++------ 2 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 src/components/databrowser/hooks/sort-object.test.ts diff --git a/src/components/databrowser/hooks/sort-object.test.ts b/src/components/databrowser/hooks/sort-object.test.ts new file mode 100644 index 0000000..28f8f61 --- /dev/null +++ b/src/components/databrowser/hooks/sort-object.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, test } from "bun:test" + +import { sortObject } from "./use-fetch-simple-key" + +describe("sortObject", () => { + test("keeps arrays as arrays", () => { + expect(sortObject([0, "a", null])).toEqual([0, "a", null]) + }) + + test("sorts object keys recursively, including objects inside arrays", () => { + const sorted = sortObject({ b: [{ d: 1, c: [{ f: 2, e: 3 }] }], a: { z: 1, y: 2 } }) + expect(JSON.stringify(sorted)).toBe('{"a":{"y":2,"z":1},"b":[{"c":[{"e":3,"f":2}],"d":1}]}') + }) +}) diff --git a/src/components/databrowser/hooks/use-fetch-simple-key.tsx b/src/components/databrowser/hooks/use-fetch-simple-key.tsx index f29641f..a25eaba 100644 --- a/src/components/databrowser/hooks/use-fetch-simple-key.tsx +++ b/src/components/databrowser/hooks/use-fetch-simple-key.tsx @@ -25,15 +25,12 @@ export const useFetchSimpleKey = (dataKey: string, type: DataType) => { } // Add recursive key sorting to a JSON object -const sortObject = (obj: unknown): unknown => { +export const sortObject = (obj: unknown): unknown => { + if (Array.isArray(obj)) return obj.map((item) => sortObject(item)) if (typeof obj !== "object" || obj === null) return obj return Object.fromEntries( Object.entries(obj) .sort((a, b) => a[0].localeCompare(b[0])) - .map(([key, value]) => - typeof value === "object" && !Array.isArray(value) && value !== null - ? [key, sortObject(value)] - : [key, value] - ) + .map(([key, value]) => [key, sortObject(value)]) ) }