【问题标题】:How to sort JavaScript object using underscore js? [duplicate]如何使用下划线 js 对 JavaScript 对象进行排序? [复制]
【发布时间】:2016-04-23 05:36:34
【问题描述】:

以下是我的 JavaScript 对象。

{
  "014b9d42":{
    "notification": 0,
    "userName": "adam"
  },
  "02f5b60e": {
    "notification": 3,
    "userName": "jake"
  },
  "1281d8fb": {
    "notification": 1,
    "userName": "eomer"
  },
  "12a2a564": {
    "notification": 0,
    "userName": "bella"
  }
}

我想根据通知的值对上述对象进行排序。如何使用下划线 js 做到这一点?

【问题讨论】:

  • 对象中没有顺序
  • 你会想要一个数组而不是一个对象。也许让你的对象的键成为另一个属性,这样你就可以拥有一个对象数组

标签: javascript sorting underscore.js


【解决方案1】:

正如@adeneo 指出的那样,order in objects is not guaranteed。您需要将对象转换为数组,然后根据notification 属性进行排序。

var jsonObj = JSON;

var arr = [];
for (var key in jsonObj) {
  if (jsonObj.hasOwnProperty(key)) {
    var o = jsonObj[key];
    arr.push({ id: key, notification: o.notification, userName: o.userName });
  }
}

arr.sort(function(obj1, obj2) {
  return obj1.notification - obj2.notification;
});

这是working JSFiddle

【讨论】:

    【解决方案2】:

    您提供的 JSON 不是列表。因此无法排序。如果这是一个列表,那么您可以使用以下代码:

    var a = [
        {"014b9d42": {
            "notification": 0,
            "userName": "adam"
        }},
        {"02f5b60e": {
            "notification": 3,
            "userName": "jake"
        }},
        {"1281d8fb": {
            "notification": 1,
            "userName": "eomer"
        }},
        {"12a2a564": {
            "notification": 0,
            "userName": "bella"
        }}
    ];
    
    var sorted = _.sortBy(a, function(item) { 
       var key = [Object.keys(item)[0]];
       return item[key]['notification']; 
    });
    
    console.log(sorted);
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 2013-12-31
      • 1970-01-01
      • 2016-08-05
      • 2015-12-30
      • 2019-11-22
      • 1970-01-01
      • 2019-06-05
      • 2018-02-02
      相关资源
      最近更新 更多