编程语言
首页 > 编程语言> > javascript-按值对对象排序

javascript-按值对对象排序

作者:互联网

我在使用Underscore时遇到困难.我想按其值的字母顺序对下面的对象进行排序,并以相同的格式返回它.

{
  "accommodation" : "Accommodation",
  "bed-breakfast" : "Bed & Breakfast",
  "caravan-camping" : "Caravan & Camping",
  "cottages" : "Cottages",
  "friends-family" : "Friends & Family",
  "health-spas" : "Health Spas",
  "hostels" : "Hostels",
  "hotels" : "Hotels",
  "self-catering" : "Self Catering",
  "backpacking" : "Backpacking",
  "car-touring" : "Car Touring"
}

我已经设法对其进行排序,但是它用索引值替换了键.有任何想法吗?这应该是相当简单的.我想念什么?

提前致谢!

解决方法:

您无法可靠地对JavaScript对象进行排序. ES5 section 12.6.4说:

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

15.2.3.7节说:

If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used to order the list elements in step 3 of this algorithm.

Section 15.2.3.14(Object.keys)说:

If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used in step 5 of this algorithm.

您也可以查看8.6 The Object Type部分,以查看是否有任何有关财产顺序的提示(提示:没有).因此,在ES5中,属性顺序取决于实现,并且唯一的限制或多或少是,如果在任何地方都有定义的顺序,则该顺序在任何地方都必须相同.

ES6草案在section 9.1.11中包含类似的语言:

The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

因此,对对象中的事物绝对没有可移植且可靠的顺序.

不,您不能通过JSON作为JSON defines an object as

… an unordered set of name/value pairs

某些JavaScript实现会按插入顺序对对象进行排序,但是您不能依赖它.

最好的办法是将您的Object转换为具有以下内容的数组:

var sorted = _(obj).chain()
                   .pairs()
                   .sortBy(_.last)
                   .value();

或对象数组:

var sorted2 = _(obj).chain()
                    .pairs()
                    .sortBy(_.last)
                    .map(function(a) { return _([a]).object() })
                    .value();

演示:http://jsfiddle.net/ambiguous/76ZPx/

标签:javascript,underscore-js
来源: https://codeday.me/bug/20191012/1901477.html