通过排序值的Javascript对象 [英] Sorting a Javascript object by value

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

问题描述

在我的JavaScript应用程序,我有一个对象,我需要能够通过内部对象内的值订购阵列。

In my Javascript application I have an Object and I need to be able to order the array by a value within the Inner Object.

例如:

{
    a : {
        timestamp: xxxxxx
        other : yyyyyy
    },
    b : {
        timestamp: xxxxxx
        other : yyyyyy
    },
    c : {
        timestamp: xxxxxx
        other : yyyyyy
    }
}

我需要做的是根据每个内部对象的时间戳管理这些数据集和重新排序的数组。

What I need to do is manage this data set and re-order the array according to the timestamp of each inner object.

哪些途径他们,我可以做这样做?

What ways are they that I can do to do this?

更新:

我最初的想法会做一些像这样:

My initial thought would be doing something like so:

{
    a : {},
    b : {},
    c : {},
    _ : [
        c, a, b //Key's Only
    ]
}

然后重新索引基于这样的价值观的对象,这将理清如何索引的对象,但是当我插入一个新元素我也必须重新生成 _ 指数的关系,这似乎办法不多的努力。

Then re-indexing the the object based on those values, that would sort out how to index the object, but when I insert a new element i would also have to regenerate the _ index relationship which seems way to much effort.

推荐答案

您可以将数据复制到一个数组,然后排序的:

You can copy the data to an array and then sort it:

var data = {
    a : {
        timestamp: 11111,
        other : "xxx"
    },
    b : {
        timestamp: 22222,
        other : "yyy"
    },
    c : {
        timestamp: 33333,
        other : "zzz"
    }
};

var output = [];

// copy items to an array so they can be sorted
for (var key in data) {
    data[key].key = key;   // save key so you can access it from the array (will modify original data)
    output.push(data[key]);
}    

output.sort(function(a,b) {
    return(a.timestamp - b.timestamp);
});

生成此作为输出(注意我说原来的关键对象,因此它的访问从数组):

Generates this as output (note I added the original key to the object so it's accessible from the array):

[{"timestamp":11111,"other":"xxx","key":"a"},
{"timestamp":22222,"other":"yyy","key":"b"},
{"timestamp":33333,"other":"zzz","key":"c"}]

您可以看到这方面的工作在这里: http://jsfiddle.net/jfriend00/hXpkP/

You can see this working here: http://jsfiddle.net/jfriend00/hXpkP/

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

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