Lodash sort list of objects based on key

ぃ、小莉子 提交于 2019-12-07 15:08:31

问题


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.


回答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;



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



来源:https://stackoverflow.com/questions/42827133/lodash-sort-list-of-objects-based-on-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!