简体   繁体   English

如何按每个对象内特定键的alpha对Array排序?

[英]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: 当前在用户界面中,数组如下所示:

  • leon 里昂
  • laura 劳拉
  • anne 安妮

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);
});

jsFiddle: https://jsfiddle.net/p07c4oaa/ jsFiddle: https ://jsfiddle.net/p07c4oaa/

Or wrap that in a function like: 或将其包装在类似以下的函数中:

function sortBy(obj, key) {
  return obj.sort(function(a, b) {
    return a[key].localeCompare(b[key]);
  });
}

jsFiddle: https://jsfiddle.net/p07c4oaa/1/ jsFiddle: https ://jsfiddle.net/p07c4oaa/1/

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>')

})

JSFIDDLE JSFIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM