diff --git a/src/lib/logic/sort.test.ts b/src/lib/logic/sort.test.ts index e17b476a..7a1d74c2 100644 --- a/src/lib/logic/sort.test.ts +++ b/src/lib/logic/sort.test.ts @@ -33,7 +33,7 @@ describe('sort', () => { ]) }) - test('should sort object keys using a rootPath', () => { + test('should sort a nested object inside an object', () => { const object = { root: { path: { b: 1, c: 1, a: 1 } @@ -47,6 +47,16 @@ describe('sort', () => { ]) }) + test('should sort a nested object inside an array', () => { + const object = [{ b: 1, c: 1, a: 1 }] + + assert.deepStrictEqual(sortJson(object, ['0']), [ + { op: 'move', from: '/0/a', path: '/0/a' }, + { op: 'move', from: '/0/b', path: '/0/b' }, + { op: 'move', from: '/0/c', path: '/0/c' } + ]) + }) + test('should sort an array', () => { assert.deepStrictEqual(sortJson([2, 3, 1]), [{ op: 'replace', path: '', value: [1, 2, 3] }]) assert.deepStrictEqual(sortJson([2, 3, 1], undefined, undefined, -1), [ diff --git a/src/lib/logic/sort.ts b/src/lib/logic/sort.ts index a2922f46..0cf72044 100644 --- a/src/lib/logic/sort.ts +++ b/src/lib/logic/sort.ts @@ -38,7 +38,9 @@ export function sortJson( itemPath: JSONPath = [], direction: 1 | -1 = 1 ): JSONPatchDocument { - if (isJSONArray(getIn(json, rootPath))) { + const value = getIn(json, rootPath) + + if (isJSONArray(value)) { if (itemPath === undefined) { throw new Error('Cannot sort: no property selected by which to sort the array') } @@ -46,7 +48,7 @@ export function sortJson( return sortArray(json, rootPath, itemPath, direction) } - if (isObject(json)) { + if (isObject(value)) { return sortObjectKeys(json, rootPath, direction) }