feature: Add support for nested object fields in Data Table

feature: Add support for nested object fields in Data Table
This commit is contained in:
Khiman Louer 2021-04-16 19:23:39 +02:00
commit a6c5e570f3
No known key found for this signature in database
GPG key ID: 0B94B91AB55C831D

View file

@ -124,6 +124,14 @@
.map(({ key }, i) => ({ key, id: $headerItems[i] })) .map(({ key }, i) => ({ key, id: $headerItems[i] }))
.reduce((a, c) => ({ ...a, [c.key]: c.id }), {}) .reduce((a, c) => ({ ...a, [c.key]: c.id }), {})
); );
const resolvePath = (object, path, defaultValue) =>
path
.split(/[\.\[\]\'\"]/)
.filter((p) => p)
.reduce(
(o, p) => (o && typeof o === "object" && o[p] ? o[p] : defaultValue),
object
);
setContext("DataTable", { setContext("DataTable", {
sortHeader, sortHeader,
@ -159,7 +167,7 @@
$: headerKeys = headers.map(({ key }) => key); $: headerKeys = headers.map(({ key }) => key);
$: rows = rows.map((row) => ({ $: rows = rows.map((row) => ({
...row, ...row,
cells: headerKeys.map((key) => ({ key, value: row[key] })), cells: headerKeys.map((key) => ({ key, value: resolvePath(row, key, "") })),
})); }));
$: sortedRows = rows; $: sortedRows = rows;
$: ascending = $sortHeader.sortDirection === "ascending"; $: ascending = $sortHeader.sortDirection === "ascending";
@ -170,8 +178,12 @@
sortedRows = rows; sortedRows = rows;
} else { } else {
sortedRows = [...rows].sort((a, b) => { sortedRows = [...rows].sort((a, b) => {
const itemA = ascending ? a[sortKey] : b[sortKey]; const itemA = ascending
const itemB = ascending ? b[sortKey] : a[sortKey]; ? resolvePath(a, sortKey, "")
: resolvePath(b, sortKey, "");
const itemB = ascending
? resolvePath(b, sortKey, "")
: resolvePath(a, sortKey, "");
if ($sortHeader.sort) return $sortHeader.sort(itemA, itemB); if ($sortHeader.sort) return $sortHeader.sort(itemA, itemB);