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.
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;
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]]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With