Lodash - sort objects in object ( desc and asc)

倾然丶 夕夏残阳落幕 提交于 2019-12-11 10:47:07

问题


How to sort object of objects asc and desc using Lodash?

For example i want to sort it by 'r' or 'd'.

This is how my object looks like:


回答1:


Place internal objects in array and use function sortBy()

var users = [
 { 'user': 'fred',   'age': 48 },
 { 'user': 'barney', 'age': 36 },
 { 'user': 'fred',   'age': 40 },
 { 'user': 'barney', 'age': 34 }
];

_.sortBy(users, function(o) { return o.user; });
// → objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
console.log(users.reverse()); // desc order



回答2:


Pure JS is also very simple and you may do something like this;

var   obj = {a:16, b:2, c:8, d:4, e:1},
    okeys = Object.keys(obj),
   sorted = {};
okeys.sort((p,c) => obj[p] <= obj[c]).forEach((p,i) => sorted[okeys[i]] = obj[p]);
document.write('<pre> ' + JSON.stringify(sorted, 0, 2) + '</pre>');

I am sorting object properties according to their numerical values. Their values could be objects and you could sort according to these objects property values as well. But i can not comment on what could be a sensible reason behind doing all this.



来源:https://stackoverflow.com/questions/36644531/lodash-sort-objects-in-object-desc-and-asc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!