按对象键在Javascript/下划线上按降序排序 [英] Sort by object key in descending order on Javascript/underscore

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

问题描述

我有以下对象数组,其中的键是UTC格式的日期.

I have the following object array where the key is the date in UTC format.

    Array = [{1436796000000:["Task1","Task2"],
         1437400800000:["Task4","Task8"],
         1436968800000: ["Task3","Task2"],
         1436882400000:["Task5","Task6"]}]

我想按键对数组对象进行降序排序.因此,预期的输出将紧随其后,例如最晚的日期将排在最前.

I want to sort this array object by key in descending order. So the expected output will be following like the latest date will come first.

    Array = [{1437400800000:["Task4","Task8"],
             1436968800000: ["Task3","Task2"],
             1436882400000:["Task5","Task6"],
             1436796000000:["Task1","Task2"]}]

我该如何在javascript中或使用underscore.js?

How can I do this in javascript or using underscore.js?

推荐答案

否,这不是数组,而是对象,而Javascript对象的属性按定义是无序的;因此对它们进行分类是没有意义的.

No, that isn't an array, it's an object, and Javascript objects' properties are unordered by definition; so sorting them is meaningless.

您可以改为使用一个有序的数组,然后像这样重组数据:

You could instead use an array, which does have order, and restructure your data like this:

var arr = [
  { date: 1436796000000, value: ["Task1","Task2"] },
  { date: 1437400800000, value: ["Task4","Task8"] },
  { date: 1436968800000, value: ["Task3","Task2"] },
  { date: 1436882400000, value: ["Task5","Task6"] }
]

,然后您可以按日期对其进行排序:

and then you can sort it by date:

arr.sort( function ( a, b ) { return b.date - a.date; } );

如果您不想重组数据,则可以按所需顺序进行遍历,方法是获取其键的数组并对该数组进行排序,然后使用该数组访问对象的属性,但是您将每次您想要以特定顺序遍历该对象时,都需要执行此操作,因为该对象中仍然没有存储顺序信息:

If you don't want to restructure your data, you can iterate through it in the order you want, by getting an array of its keys and sorting that array, then using that array to access your object's properties, but you will need to do this each time your want to iterate through it in a particular order, since there is still no order information stored in the object:

// Get the array of keys
var keys = Object.keys( obj );

// Sort the keys in descending order
keys.sort( function ( a, b ) { return b - a; } );

// Iterate through the array of keys and access the corresponding object properties
for ( var i = 0; i < keys.length; i++ ) {
    console.log( keys[i], obj[ keys[i] ] );
}

您将需要填充 Object.keys 支持IE 8和更低版本的浏览器.

You will need to shim Object.keys to support IE 8 and older browsers.

这篇关于按对象键在Javascript/下划线上按降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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