Lodash sort list of objects based on key

26,843

Solution 1

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;

Solution 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]].

Share:
26,843
Sam
Author by

Sam

Updated on July 09, 2022

Comments

  • Sam
    Sam almost 2 years

    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.

  • Matt
    Matt about 7 years
    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!