如何解决使用动态方法对数组的嵌套对象进行排序
要排序的样本对象:
{
"content": [
{
"rows": [
{
"cells": [
{
"value": "99","name": "myname"
}
],"hash": "f6a1234a5475acd50de4f94c462a6f3d","isUsed": true
}
],"id": "MYTABLE_CUST","columns": [
{
"name": "MNS","exists": true
},{
"name": "OPQ","exists": true
}
],"tableId": "MYTABLE_CUST","viewId": "MNO_OPQ_RST_UVW","viewDescription": "Customer View of Table","viewItemId": "MYTABLE_CUST"
}
]
}
您可以使用http://jsonviewer.stack.hu/可视化该对象
我正在排序此对象的每个数组。我正在整理-
一世。内容->通过viewId和id
ii。内容->按名称列
iii。内容->按哈希行
iv。内容->行->按名称命名的单元格
现在,我想要一个更动态的方法,而不是去研究逻辑并每次更改要对其进行排序的属性ID(在本例中为viewId,name,hash和name),我想创建一个包含此规则的JSON映射。
例如,以下是我想到的-
{
"rules": [
{
"type": "BCBS","sortingProperties": [{
"content": {
"base": "",//if base empty sort on it
"fields": ["viewId","id"]
},"columns": {
"base": "content",//sort on content -> columns
"fields": ["name","description"]
},"rows": {
"base": "content",//sort on content -> rows
"fields": ["name"]
},"cells": {
"base": "content#rows",//use splice and sort on content -> rows -> cells
"fields": ["id"]
}
}]
}
]
}
-
我们可以使用比此更好的JSON或映射来定义这些按属性排序数组的规则吗?
-
除了地图以外,您是否知道其他任何序列化和反序列化方法,以使按其属性对此类复杂嵌套对象的排序更加动态?
-
还有哪些其他地方可以改善此地图的体系结构或性能?
我正在使用 TypeScript 。
我当前正在使用的用于排序逻辑的CodeSnippet-
致电-
obj.content.sort(this.sortByProperty("viewId"));
obj.content.forEach(e => {
if (e.columns && e.columns.length > 0) {
e.columns.sort(this.sortByProperty("name"));
}
})
辅助方法-
private sortByProperty (property: string) {
return (a,b) => {
if (a[property] && b[property]) {
if (typeof a[property] === "string") {
return a[property].localeCompare(b[property]);
}
if (typeof a[property] === "number") {
return a[property] - b[property];
}
}
}
}
private sortByMultipleProperties (prop1: string,prop2: string) {
return this.sortByProperty(prop1) || this.sortByProperty(prop2);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。