Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash sort list of objects based on key

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.

like image 513
Sam Avatar asked Mar 16 '17 06:03

Sam


2 Answers

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;
like image 101
Martin Schneider Avatar answered Nov 14 '22 03:11

Martin Schneider


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

like image 24
yureka Avatar answered Nov 14 '22 02:11

yureka