Skip to content

Commit

Permalink
fix: cannot sort a nested object inside an array
Browse files Browse the repository at this point in the history
  • Loading branch information
josdejong committed Nov 4, 2024
1 parent 3ae89d9 commit 5ebe9fc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
12 changes: 11 additions & 1 deletion src/lib/logic/sort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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), [
Expand Down
6 changes: 4 additions & 2 deletions src/lib/logic/sort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ 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')
}

return sortArray(json, rootPath, itemPath, direction)
}

if (isObject(json)) {
if (isObject(value)) {
return sortObjectKeys(json, rootPath, direction)
}

Expand Down

0 comments on commit 5ebe9fc

Please sign in to comment.