最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sorting an array of objects by keyname in javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Nov 19, 2013 at 22:22 thugsbthugsb 23.4k6 gold badges32 silver badges44 bronze badges 2
  • 3 possible duplicate of Sorting an array of JavaScript objects – Roland Illig Commented Nov 19, 2013 at 22:24
  • It's not a duplicate. That question wanted to sort by a known key that exists in each object in the array. This question wants to sort by the key name itself, which is different from object to object. – thugsb Commented Nov 20, 2013 at 14:43
Add a ment  | 

2 Answers 2

Reset to default 8

Something like this using Array.sort(pareFunction) ?

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

PSL's answer have one problem that is if your array has uppercase and lowercase keys i.e. "john", "Naveed" then this solution is not going to work correctly. Following changes need to be done:

let source = [{"john": 12},{"Ali": 10},{"Naveed": 18}];

var target = source.sort(function(a,b){
 return (Object.keys(a)[0].toLowerCase() > Object.keys(b)[0].toLowerCase()) - 0.5;
});
console.log(target);
发布评论

评论列表(0)

  1. 暂无评论