【发布时间】:2021-02-18 06:14:34
【问题描述】:
Hi 动态获取 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",
"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":789
},
{
"Date":"2020-10-16T04:21:41+00:00",
"applicationName":"app Hub",
"status":{
"statusname":"Failure",
"style":"error"
},
"details":{
"maindescription":"welcome to the application",
"maindescriptionSecn":"description 2",
"maindescriptionSecnthrid":"description 3"
},
"location":"Sondekoppa, Karnataka, IN",
"ipAddress":"157.49.147.190",
"count":666
}
]
【问题讨论】:
-
只是想告诉您,您的 JSON 示例无效。删除结尾的逗号。
-
@Rumplin 更正了格式。
-
@RameshLamani 您是使用 redux 进行排序还是尝试对组件内的整个内容进行排序?
-
想澄清一下,您一次只能对一个属性进行排序。这就是您的问题的解读方式。
-
我一直发现从要对其进行排序的属性构建复合值非常简单直接。当值包含数字和日期时,这更难(但并非不可能)。
标签: javascript json reactjs ecmascript-6 ecmascript-5