Lodash sort list of objects based on key
Asked Answered
D

3

9

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.

Dygall answered 16/3, 2017 at 6:52 Comment(5)
Possible duplicate of Sort JavaScript object by keyCullet
@MartinSchneider I am looking solution using lodashDygall
from the linked Question: 'JavaScript objects are not ordered. It is meaningless to try to "sort" them. 'Cullet
@MartinSchneider That's been changed in ES2015. String keys will iterate in creation order.Seaquake
i stand corrected: in es2015 the keys will iterate in creation order, @Seaquake is right.Cullet
C
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;
Cullet answered 16/3, 2017 at 8:48 Comment(1)
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!Seaquake
S
4

Here's a one-liner using lodash:

_.pick(obj, Object.keys(obj).sort());

pick will return a new object with the keys in the order specified by the second argument.

Selfrealization answered 15/12, 2023 at 2:26 Comment(1)
awesome deserves more upvotesInteroffice
H
3

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

Hydrotherapy answered 22/6, 2017 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.