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?
_.sortBy(myObjects, 'name');
名称是此处的排序键
You do not need lodash to do that...
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
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>')
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.