我们如何自定义排序JavaScript对象键? [英] How can we custom sort JavaScript object keys?

查看:117
本文介绍了我们如何自定义排序JavaScript对象键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图自定义排序JavaScript对象,但无法得到我们如何以正确的方式做到这一点。假设我有一个对象,例如:

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

我有一个数组值为: var arr = ['red','green','blue','yellow'];

所以在排序之后,我想按照数组中指定的顺序输出,比如

< $ p $ lt; code> var test = {
'red':[],
'green':[],
'blue':[],
'yellow':[]
}

但由于某些原因,我不是能够实现这一点。这里要做的是循环和排序,但它排序在AZ模式,而不是按照我指定数组的顺序。另外,你可能会问,甚至没有在排序函数中使用我的数组,但没有得到

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

var keys = Object.keys(test);

console.log(keys.sort()); // [蓝色,绿色,红色,黄色]这是没有命令也不是它的对象

任何方向都有帮助。




注意:我有这个特定的需求,因为我使用的是HandleBars使用默认的 {{#each}} 块,但我想循环内部对象的顺序。我可以循环使用Handlebars中的对象并将它们传递给模板,但不会使用模板引擎的功能。我需要把手来循环它们还是我错过了什么?如果我循环对象并将整个标记传递给句柄模板,那么这很好吗。

解决方案

JavaScript对象是散列并因此固有地联合-ordered。您无法以任何给定顺序制作具有属性的对象。如果您在枚举键时收到了一个排序,那纯粹是巧合,或者说是JavaScript引擎的实现细节。



您必须使用一个对象数组来实现你想要做的事情。



换句话说,你选择的数据结构是不可能的。 b $ b

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.

解决方案

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.

这篇关于我们如何自定义排序JavaScript对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆