问题描述
您好,动态获取JOSN数据,基于JOSN会在表中呈现数据。在JSON中,嵌套对象来了,那些名称和属性键也动态地出现了。我需要根据表格上的列上下按钮操作ASC和DESC进行排序。在按钮操作上,我得到了要排序的属性名称,这些属性键名称将放置在嵌套对象内,或者可能在上层。如何动态识别和排序数字,字符串或日期。非常感谢。
在逻辑上,我仅添加了对单级JSON对象的工作,而不对嵌套级对象进行工作。
dynamicJSON.sort((a,b) => {
if (a[sortKeyname] < b[sortKeyname]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortKeyname] > b[sortKeyname]) {
return sortConfig.direction === 'ascending' ? 1 : -1;
}
return 0;
});
以下是示例动态JSON数据
从下面的JSON中,我有7列,如果选择状态列ASC / DESC按钮,则会获得 statusname 属性进行排序。它应该根据键属性 statusname 遍历和排序嵌套的JSON对象。如果我选择“详细信息”列ASC / DESC按钮,则会得到 maindescription 属性进行排序。它应该根据键属性 maindescription 遍历和排序嵌套的JSON对象。
[
{
"Date":"2020-10-16T04:15:58+00:00","applicationName":"abc Portal","status":{
"statusname":"Success","style":"success"
},"details":{
"maindescription":"welcome to the application","maindescriptionSecn":"description 2","maindescriptionSecnthrid":"description 3"
},"location":"Sondekoppa,Karnataka,IN","ipAddress":"157.49.147.190","count":123
},{
"Date":"2020-10-16T04:15:56+00:00","applicationName":"poratl 1","count":789
},{
"Date":"2020-10-16T04:21:41+00:00","applicationName":"app Hub","status":{
"statusname":"Failure","style":"error"
},"count":666
}
]
解决方法
您可以在所需的一个或多个键和方向上使用闭包,并使用返回的函数进行排序。
排序功能使用将交出的键字符串按点分隔并从(嵌套的)对象获取值的功能。
const
sortBy = (key,direction = 'ascending') => (a,b) => {
const
factor = +(direction === 'ascending') || -1,getValue = (object,keys) => keys.split('.').reduce((o,k) => o?.[k],object),valueA = getValue(a,key),valueB = getValue(b,key);
return factor * (valueA > valueB || -(valueA < valueB));
},data = [{ Date: "2020-10-16T04:15:58+00:00",applicationName: "IAM Portal/IAM Portal",status: { foo: 'b',statusname: "Success",style: "success" },details: { maindescription: "welcome to the application",maindescriptionSecn: "description 2",maindescriptionSecnthrid: "description 3" },location: "Sondekoppa,Karnataka,IN",ipAddress: "157.49.147.190",count: 123 },{ Date: "2020-10-16T04:15:56+00:00",status: { foo: 'a',count: 789 },{ Date: "2020-10-16T04:21:41+00:00",applicationName: "IAM Portal/Reports Hub",status: { foo: 'c',statusname: "Failure",style: "error" },count: 666 }];
data.sort(sortBy('status.foo'));
console.log(data);
data.sort(sortBy('status.foo','descending'));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }