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]]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.