Skip to content

Commit b699e4b

Browse files
bobzuradtmorehouse
authored andcommitted
feat(table): Support sorting on nested object properties (#1868)
1 parent a622358 commit b699e4b

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

src/components/table/README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,10 +241,12 @@ export default {
241241
sortable: true
242242
},
243243
city: {
244-
key: 'address.city'
244+
key: 'address.city',
245+
sortable: true
245246
},
246247
'address.country': {
247-
label: 'Country'
248+
label: 'Country',
249+
sortable: true
248250
}
249251
},
250252
items: [

src/components/table/table.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,31 @@ function recToString (obj) {
4040
}
4141

4242
function defaultSortCompare (a, b, sortBy) {
43-
if (typeof a[sortBy] === 'number' && typeof b[sortBy] === 'number') {
44-
return (a[sortBy] < b[sortBy] && -1) || (a[sortBy] > b[sortBy] && 1) || 0
43+
if (sortBy.indexOf('.') < 0) {
44+
return sort(a[sortBy], b[sortBy])
45+
} else {
46+
return sort(getNestedValue(a, sortBy), getNestedValue(b, sortBy))
4547
}
46-
return toString(a[sortBy]).localeCompare(toString(b[sortBy]), undefined, {
48+
}
49+
50+
function sort (a, b) {
51+
if (typeof a === 'number' && typeof b === 'number') {
52+
return (a < b && -1) || (a > b && 1) || 0
53+
}
54+
return toString(a).localeCompare(toString(b), undefined, {
4755
numeric: true
4856
})
4957
}
5058

59+
function getNestedValue (obj, path) {
60+
path = path.split('.')
61+
var value = obj
62+
for (var i = 0; i < path.length; i++) {
63+
value = value[path[i]]
64+
}
65+
return value
66+
}
67+
5168
function processField (key, value) {
5269
let field = null
5370
if (typeof value === 'string') {

0 commit comments

Comments
 (0)