8

I am looking for sorting the list of objects based on key

Here is my object

var Categories =    {

      "social": [
        {
          "id": "social_001",
          "lastModified": "2 Day ago"
        }
      ],
"communication": [
        {
          "id": "communication_001",
          "lastModified": "4 Day ago"
        },
        {
          "id": "communication_002",
          "lastModified": "1 Day ago"
        }
      ],
      "storage": [
        {
          "id": "storage_001",
          "lastModified": "3 Day ago"
        }
      ]
    }

so in output sorted object will sort as start with communication, social , storage suggest me some help.

Sam
  • 795
  • 2
  • 18
  • 31

2 Answers2

14

Here is a solution using lodash:

var Categories = {
  "social": [
    {
      "id": "social_001",
      "lastModified": "2 Day ago"
    }
  ],
  "communication": [
    {
      "id": "communication_001",
      "lastModified": "4 Day ago"
    },
    {
      "id": "communication_002",
      "lastModified": "1 Day ago"
    }
  ],
  "storage": [
    {
      "id": "storage_001",
      "lastModified": "3 Day ago"
    }
  ]
}

var ordered = {};   
_(Categories).keys().sort().each(function (key) {
  ordered[key] = Categories[key];
});

Categories = ordered;
Martin Schneider
  • 3,268
  • 4
  • 19
  • 29
  • 14
    lodash actually ends up not much different to the native code for this `Object.keys(Categories).sort().forEach(key => o[key] = Categories[key])`. Even if you use `.reduce` both are still the same! – Matt Mar 16 '17 at 12:37
2

Get the key array from your object using lodash _.keys or Object.keys and sort that array using JavaScript's sort() or sort().reverse() for ascending or descending order.

Then use this array for picking up each object by yourObject[array[0]].

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
yureka
  • 89
  • 8