2

My JSON object consists of several nestings:

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

In this JSON I want to sort the data in the seperate groups in "0" and "yearlyResults" in ascending order....

My Code:

/**
   * 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'));
...
}
}
}

My solution approach works, however I don't find it efficient enough! With two groups it is still ok to sort so, but if I have 20 or 30 I can no longer perform so. Can I sort the JSON groups by iterating somehow? Can you help me please?

2 Answers2

0

You can you Object.entries in order to iterate thought all key-value pairs and then use Array.prototype.reduce for composing the new object. Like so:

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);
Yuriy Yakym
  • 3,616
  • 17
  • 30
  • By ...group i have Error TS2698: Spread types may only be created from object types. –  Jun 29 '21 at 09:00
  • This might help to fix the problem: https://stackoverflow.com/questions/51189388/typescript-spread-types-may-only-be-created-from-object-types – Yuriy Yakym Jun 29 '21 at 09:03
0

Here in the snippet everything runs without errors.I have the problem in the IDE. I have implemented the code like this:

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