I have the following object key structure:
var obj = {
"1": {name: "test", groups: [...]},
"2": {name: "best", groups: [...]},
"4": {name: "pick", groups: [...]}
}
I would like to sort 'obj' by property 'name' value.
Desired outcome:
var obj = {
"2": {name: "best", groups: [...]},
"4": {name: "pick", groups: [...]},
"1": {name: "test", groups: [...]}
}
What I have tried so far using lodash libraries toPairs(), fromPairs() and sortBy() methods:
var toPairs = _.toPairs(obj);
var test = _.sortBy(toPairs, [function (o) {
return o[1].name;
}]);
'test' variable contains an array where the values are sorted as it is desired:
'test' output:
[["2", {name: "best", ...}], ["4", {name: "pick", ...}],["1", {name: "test"}]]
But when I am using fromPairs() method to convert the array back to object the result object is not sorted:
var sortedObj = _.fromPairs(test);
'SortedObj' output:
{
"1": {name: "test", groups: [...]},
"2": {name: "best", groups: [...]},
"4": {name: "pick", groups: [...]}
}