按值排序对象 [英] Sorting an object by value

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

问题描述

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

I'm having difficulty with this using Underscore. I'd like to sort the below object alphabetically by its value, and return it in the same format.

{
  "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"
}

我设法对它进行排序但是它用索引值替换键。有任何想法吗?这应该是相当直接的。我错过了什么?

I've managed to sort it but it replaces the key with an index value. Any ideas? This should be fairly straight forward. What am I missing?

提前致谢!

推荐答案

谢谢对于'mu太短的答案,它已经让我大部分时间。但是,它需要转换回一个对象,经过一些摆弄后,它非常简单。以下是完整的答案:

Thanks to 'mu is too short's answer, it has got me most of the way. However, it needs to be converted back to an object, and after some fiddling around, It's very simple. Here's the complete answer:

var sortedDataArr = _(data).chain()
                           .pairs()
                           .sortBy(_.last)
                           .value();

var sortedDataObj = _.object( sortedDataArr );

这篇关于按值排序对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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