简体   繁体   English

在javascript中按键名对对象数组进行排序

[英]Sorting an array of objects by keyname in javascript

How do I sort this array: 如何对此数组进行排序:

[{"qwe":4}, {"rty":5}, {"asd":2}]

To get this: 要得到这个:

[{"asd":2}, {"qwe":4}, {"rty":5}]

So that the array is sorted by the name of the key of the objects? 那么数组是按对象键的名称排序的?

Something like this using Array.sort(compareFunction) ? 使用Array.sort(compareFunction)这样的东西?

var myArray =[{"qwe":4}, {"rty":5}, {"asd":2}];
myArray.sort(function(a,b){
    return (Object.keys(a)[0] > Object.keys(b)[0]) - 0.5;
});
console.log(myArray);

Demo 演示

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

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