首页 > 解决方案 > How to Sort Dates, Numbers, Strings from the array of nested JSON objects in Javascript

问题描述

Hi get the JOSN data dynamically, based on the JOSN will render data in the table. In the JSON nested objects come and those names and properties keys also dynamically. I need to sort based on the table columns up and down button action ASC and DESC. On button action, I get the property names to sort, that properties key names will be placed inside the nested objects or it might be in the upper level. How to identify and sort dynamically number, strings or dates. Greate appreciate.

Below logic, I have added only work for the Single level JSON objects, not nested level objects.

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;
        });

Below is the Sample Dynamic JSON data

From the below JSON, I have 7 columns, If I select the status column ASC/ DESC button, I get statusname property for the sort. it should traverse and sort nested JSON objects based on the key properties statusname. In case, if I select the Details column ASC/ DESC button,I get maindescription property for the sort. it should traverse and sort nested JSON objects based on the key properties maindescription.

[
   {
      "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
   }
]

标签: javascriptjsonreactjsecmascript-6ecmascript-5

解决方案


您可以对想要的键/键和方向使用闭包,并使用返回的函数进行排序。

排序功能使用按点分割移交的键字符串并从(嵌套)对象中获取值的函数。

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", applicationName: "IAM Portal/IAM Portal", status: { foo: 'a', 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: "IAM Portal/Reports Hub", status: { foo: 'c', 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 }];

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; }


推荐阅读