【问题标题】:How can I sort a complex JSON object efficiently?如何有效地对复杂的 JSON 对象进行排序?
【发布时间】:2021-09-11 10:27:06
【问题描述】:

我的 JSON 对象由几个嵌套组成:

{
"myJson": {
  "firstGroup": {
"0": [
                {
                    "month": 1.0,
                    "amount": 1.7791170955479318,
                    "name": "dummy1",
                    "nr": 3
                },
                {
                    "month": 2.0,
                    "amount": 324.0,
                    "name": "dummy2",
                    "nr": 1
                },
                {
                    "month": 3.0,
                    "amount": 32323.0,
                    "name": "dummy3",
                    "nr": 2
                }
],
"yearlyResults": {
"0": [
{
                    "month": 1.0,
                    "amount": 100000,
                    "name": "dummy1",
                    "nr": 3
                },
                {
                    "month": 2.0,
                    "amount": 3000000,
                    "name": "dummy2",
                    "nr": 1
                },
                {
                    "month": 3.0,
                    "amount": 60000,
                    "name": "dummy3",
                    "nr": 2
                }
]
}           
 },
 "secondGroup": {
// Built the same way as firstGroup 
 }
},
"success": true
}

在这个 JSON 中,我想按升序对“0”和“yearlyResults”中单独组中的数据进行排序......

我的代码:

/**
   * Function to sort data ascending
   * @param property any
   */
  sortByProperty(property) {
    return (a, b) => {
      if (a[property] > b[property]) {
        return 1;
      }
      else if (a[property] < b[property]) {
        return -1;
      }
      return 0;
    };
  }
 /**
   * Show sorted data in this function
   */
private getSortedData() {
this.myService.getData().subscribe();
(resp: any) => {
const data = resp.success ? resp.myJson : null;
        // firstGroup for sort
        const firstData = data['firstGroup'];
        const currentFirstData = firstData['0'];
        const currentFirstYearly = firstData.yearlyResults['0'];

         // secondGroup for sort
        const secondData = data['secondGroup'];
        const currentSecondData = secondData['0'];
        const currentSecondYearly = secondData.yearlyResults['0'];

  if (null !== data && data) {
 currentFirstData.sort(this.sortByProperty('nr'));
 currentFirstYearly.sort(this.sortByProperty('nr'));
 currentcurrentSecondData.sort(this.sortByProperty('nr'));
 currentSecondYearly.sort(this.sortByProperty('nr'));
...
}
}
}

我的解决方案可行,但我觉得它不够高效!有两组仍然可以排序,但如果我有 20 或 30 组,我就不能再这样做了。我可以通过某种方式迭代对 JSON 组进行排序吗?你能帮帮我吗?

【问题讨论】:

  • 您要对所有组进行排序吗?还是具体的?
  • 我要对所有组进行排序
  • 所有组的结构都相同。有“0”和“yearlyResults”。这些将按升序排列。你知道怎么做吗?
  • 只能有“1”、“2”等还是“0”?
  • 是的,也可能有 1,2,3。但我只在 0 中排序

标签: javascript json angular typescript


【解决方案1】:

在 sn-p 中,一切运行都没有错误。我在 IDE 中遇到了问题。我已经实现了这样的代码:

this.kpisService.getAllKpisMonthData(yearString).subscribe(
  (resp: any) => {
    const data = resp.success ? resp.kpi : null;

    // console.table(data);

    if (null !== data && data) {
      const sortSubGroupByProperty = (subGroup, property) => {
        return subGroup.sort((a, b) => {
          if (a[property] > b[property]) {
            return 1;
          }
          else if (a[property] < b[property]) {
            return -1;
          }
          return 0;
        });
      };

      const result = Object.entries(data).reduce((result, entry) => {
        const [groupName, group] = entry;
        result[groupName] = {
          ...group, // Here is the problem
          0: sortSubGroupByProperty(group[0], 'nr'),
          yearlyResults: {
            ...group.yearlyResults,
            0: sortSubGroupByProperty(group.yearlyResults[0], 'nr')
          }
        };
        return result;
      }, {});

      console.log(result);

【讨论】:

    【解决方案2】:

    您可以Object.entries 来迭代所有key-value 对,然后使用Array.prototype.reduce 来组成新对象。像这样:

    const data = JSON.parse('{ "myJson": { "firstGroup": { "0": [ { "month": 1.0, "amount": 1.7791170955479318, "name": "dummy1", "nr": 3 }, { "month": 2.0, "amount": 324.0, "name": "dummy2", "nr": 1 }, { "month": 3.0, "amount": 32323.0, "name": "dummy3", "nr": 2 } ], "yearlyResults": { "0": [ { "month": 1.0, "amount": 100000, "name": "dummy1", "nr": 3 }, { "month": 2.0, "amount": 3000000, "name": "dummy2", "nr": 1 }, { "month": 3.0, "amount": 60000, "name": "dummy3", "nr": 2 } ] } } }, "success": true }');
    
    const object = data.myJson;
    
    const sortSubGroupByProperty = (subGroup, property) => {
      return subGroup.sort((a, b) => {
        if (a[property] > b[property]) {
          return 1;
        }
        else if (a[property] < b[property]) {
          return -1;
        }
        return 0;
      });
    }
    
    const result = Object.entries(object).reduce((result, entry) => {
      const [groupName, group] = entry;
      result[groupName] = {
        ...group,
        0: sortSubGroupByProperty(group[0], 'nr'),
        yearlyResults: {
            ...group.yearlyResults,
            0: sortSubGroupByProperty(group.yearlyResults[0], 'nr')
        }
      };
      return result;
    }, {});
    
    console.log(result);

    【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 2021-06-22
    • 2019-07-02
    • 2013-07-08
    • 2016-05-08
    • 2022-11-15
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多