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.

5
  • 2
    Possible duplicate of Sort JavaScript object by key Commented Mar 16, 2017 at 6:56
  • @MartinSchneider I am looking solution using lodash Commented Mar 16, 2017 at 7:01
  • from the linked Question: 'JavaScript objects are not ordered. It is meaningless to try to "sort" them. ' Commented Mar 16, 2017 at 7:05
  • @MartinSchneider That's been changed in ES2015. String keys will iterate in creation order. Commented Mar 16, 2017 at 7:58
  • 1
    i stand corrected: in es2015 the keys will iterate in creation order, @Matt is right. Commented Mar 16, 2017 at 8:44

3 Answers 3

15

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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!
6

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.

1 Comment

awesome deserves more upvotes
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]].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.