按字典顺序对基于嵌套值的对象数组进行排序 [英] Sort a array of objects lexicographically based on a nested value
问题描述
使用Javascript,我想知道如何根据每个对象中的字符串值按字典顺序对一组对象进行排序。
Using Javascript, I would like to know how to sort lexicographically a array of objects based on a string value in each object.
考虑:
[
{
"name" : "bob",
"count" : true
"birthday" : 1972
},
{
"name" : "jill",
"count" : false
"birthday" : 1922
},
{
"name" : "Gerald",
"count" : true
"birthday" : 1920
}
]
如何按名称的字母顺序对数组进行排序?
名称值是用户名,所以我想保留字母大小写。
How can I sort the array alphabetically by name? The name values are usernames, so I would like to maintain the letter casing.
推荐答案
var obj = [...];
obj.sort(function(a,b){return a.name.localeCompare(b.name); });
请注意,这不会考虑大写(所以它会先订购以大写字母开头的所有名字所有那些以小号开头的,即Z<a
),所以你可能会发现它与添加 toUpperCase()相关
在那里。
Be aware that this will not take capitalisation into account (so it will order all names beginning with capitals before all those beginning with smalls, i.e. "Z" < "a"
), so you might find it relevant to add a toUpperCase()
in there.
你也可以使它更通用:
function sortFactory(prop) {
return function(a,b){ return a[prop].localeCompare(b[prop]); };
}
obj.sort(sortFactory('name')); // sort by name property
obj.sort(sortFactory('surname')); // sort by surname property
如果你将比较器传递给工厂,那就更通用了......
And even more generic if you pass the comparator to the factory...
这篇关于按字典顺序对基于嵌套值的对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!