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

sorting - How can we custom sort JavaScript object keys? - Stack Overflow

programmeradmin3浏览0评论

I am trying to custom sort a JavaScript object but not able to get how we can do this in a right way. Say I am having an object like

var test = {
  'yellow': [],
  'green': [],
  'red': [],
  'blue': []
}

And I have an array with values of : var arr = ['red', 'green', 'blue', 'yellow'];

So after sorting, I want to output in the order which is specified in array like

var test = {
  'red': [],
  'green': [],
  'blue': [],
  'yellow': []
}

But for some reason, I am not able to achieve that. What am trying to do here is loop and sort but it sorts in A-Z pattern and not in the order I've specified the array in. Also, you might ask that am not even using my array in the sort function but am not getting an exact way to achieve this.

var test = {
  'yellow': [],
  'green': [],
  'red': [],
  'blue': []
}

var keys = Object.keys(test);

console.log(keys.sort());  //["blue", "green", "red", "yellow"] which is not ordered nor it's an object

Any directions will he helpful.


Note: I am having this specific requirement because am using HandleBars with default {{#each}} block, but I want to loop the inner objects in that order. I can loop the objects in Handlebars and pass them to the template but than am not using the power of template engine. I want Handlebars to loop them or am I missing something? Is it fine if I loop the objects and pass the entire markup to handlebars template.

I am trying to custom sort a JavaScript object but not able to get how we can do this in a right way. Say I am having an object like

var test = {
  'yellow': [],
  'green': [],
  'red': [],
  'blue': []
}

And I have an array with values of : var arr = ['red', 'green', 'blue', 'yellow'];

So after sorting, I want to output in the order which is specified in array like

var test = {
  'red': [],
  'green': [],
  'blue': [],
  'yellow': []
}

But for some reason, I am not able to achieve that. What am trying to do here is loop and sort but it sorts in A-Z pattern and not in the order I've specified the array in. Also, you might ask that am not even using my array in the sort function but am not getting an exact way to achieve this.

var test = {
  'yellow': [],
  'green': [],
  'red': [],
  'blue': []
}

var keys = Object.keys(test);

console.log(keys.sort());  //["blue", "green", "red", "yellow"] which is not ordered nor it's an object

Any directions will he helpful.


Note: I am having this specific requirement because am using HandleBars with default {{#each}} block, but I want to loop the inner objects in that order. I can loop the objects in Handlebars and pass them to the template but than am not using the power of template engine. I want Handlebars to loop them or am I missing something? Is it fine if I loop the objects and pass the entire markup to handlebars template.

Share Improve this question edited May 5, 2016 at 17:10 Learner asked May 5, 2016 at 17:03 LearnerLearner 511 silver badge4 bronze badges 18
  • 2 Objects have no order in JavaScript. "Sorting an object" is meaningless. – Niet the Dark Absol Commented May 5, 2016 at 17:05
  • 1 As soon as an object enters JavaScript, it has no order any more. For evidence of this, try the following in Chrome: console.dir({b:1,a:2}) - you will get {a:2,b:1} as output, because Chrome presents objects with keys in alphabetical order for easier debugging. It can do this because of the lack of inherent order in objects. – Niet the Dark Absol Commented May 5, 2016 at 17:07
  • 1 @FelixKling the question you tagged is not the same, that is normal sorting, what am asking is for custom sorting. I did searched before asking this question. Please read the question before you close them. – Learner Commented May 5, 2016 at 17:11
  • 2 This is one of those times where one is trying to solve problem A, decides on a course of action B, gets stuck, and then tries to get help with B instead of asking for help with A. @Learner you should instead ask for help with your problem A, which seems to be something like 'how to display my JS object contents in a Handlebars template, ordered'. – Thernys Commented May 5, 2016 at 17:11
  • 1 @guest271314: Sure, but only if the order is known beforehand (which is the case here). But that also only works if the function receiving the data knows how to deal with Maps. And then again, if it's your code that iterates over the Map, you might as well iterate over the key array and simply access the object properties in that order. – Felix Kling Commented May 5, 2016 at 17:19
 |  Show 13 more ments

3 Answers 3

Reset to default 10

May be you could change this using JSON.stringify()

do like

var json = {     "name": "David",     "age" : 78,     "NoOfVisits" : 4   };
console.log(json);
//outputs - Object {name: "David", age: 78, NoOfVisits: 4}
//change order to NoOfVisits,age,name

var k = JSON.parse(JSON.stringify( json, ["NoOfVisits","age","name"] , 4));
console.log(k);
//outputs - Object {NoOfVisits: 4, age: 78, name: "David"} 

put the key order you want in an array and supply to the function. then parse the result back to json.

JavaScript objects are hashes and therefore inherently un-ordered. You cannot make an object with properties in any given order. If you are receiving an ordering when you enumerate the keys, it is purely coincidental, or better said, an implementation detail of the JavaScript engine.

You'd have to use an array of objects to achieve something like what you want to do.

In other words, it is not possible with the data structure you have chosen.

You could use Map()

A Map object iterates its elements in insertion order

var arr = ['red', 'green', 'blue', 'yellow'];

var map = new Map();

arr.forEach(function(val, index) {
  var obj = {};
  obj[val] = [];
  map.set(index, obj)
});

console.log(map)

发布评论

评论列表(0)

  1. 暂无评论