[英]How to sort Array by alpha of a specific key inside each object?
Example of my Array = 我的数组示例
[{
name: leon,
id: 1
}, {
name: laura
id: 20003
}, {
name: anne
id: 45
}]
Currently in the UI, the array will look like: 当前在用户界面中,数组如下所示:
How can one use lodash to sort the array by the name
keys in alphabetical order? 如何使用lodash通过
name
键按字母顺序对数组进行排序?
_.sortBy(myObjects, 'name');
名称是此处的排序键
You do not need lodash to do that... 您不需要lodash来做...
Just do 做就是了
var sortedNames = names.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
Or wrap that in a function like: 或将其包装在类似以下的函数中:
function sortBy(obj, key) {
return obj.sort(function(a, b) {
return a[key].localeCompare(b[key]);
});
}
You could use a proper callback. 您可以使用适当的回调。
var array = [{ name: 'leon', id: 1}, { name: 'laura', id: 20003}, { name: 'anne', id: 45}]; array.sort(function (a, b) { return a.name.localeCompare(b.name); }); console.log(array);
Not sure of loadash but you can use simple sort method to sort the json array of objects 不确定是否有loadash,但是您可以使用简单的排序方法对对象的json数组进行排序
var arry=[{
name: 'leon',
id: 1
}, {
name: 'laura',
id: 20003
}, {
name: 'anne',
id: 45
}]
var sorted = arry.sort(function(a,b){
return a.name > b.name ? 1:-1
})
// this part just for demo
sorted.forEach(function(item){
document.write('<pre>'+item.name+'</pre>')
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.