对象的JavaScript对象排序 [英] javascript sort object of objects

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

问题描述

我有对象的对象。 (因为我想用关联数组,所以对象的对象,对象不是数字数组)

I have an Object of Objects. (because I want to use associative array, so object of objects, not numeric array of objects)

var tasks=new Object();

for(...){
tasks[foo-i]={};
tasks[foo-i].index=....;
tasks[foo-i].name=...;
}

我有一个函数,将输出任务的名字,但他们必须按照升序排列索引是。所以,我必须有一个临时排序功能。
你会怎么做呢?
谢谢

I have a function that'll output the name of the tasks, but they have to be according to the index in ascending order. So, I'll have to have a temporary sort-function. How would you do that? Thanks

推荐答案

也许还有一个更优雅的方式,但这种方式得到的所有任务键调出的对象,将它们排序,然后通过按键的顺序原始对象使用有序索引数组循环(如果我正确理解你重新尝试做)。

Option 1: Output in order of the keys on the task object:

Perhaps there is a more elegant way, but this way gets all the tasks keys out of the object, sorts them and then uses the ordered index array to cycle through the original object in key order (if I understood correctly what you're trying to do).

var indexArray = [];
var i;
for (i in tasks) {
    indexArray.push(i);   // collect all indexes
}
indexArray.sort(function(a,b) {return(a-b);});  // sort the array in numeric order
for (i = 0; i < indexArray.length; i++) {
    console.log(tasks[indexArray[i]].name);
}

您可以使用tasks.keys的快捷方式获取对象的索引,但不是普遍可用的,所以你得有反正这样做的另一种方式。

You could use tasks.keys as a shortcut to getting the object indexes, but that is not universally available so you'd have to have an alternate way of doing it anyway.

重读你的问题,我意识到有可能是另一种方式来跨preT你的问题。也许你在索引顺序,其中它的数据的.index旁边的。名称的意思,而不是任务的索引键对象。如果是这样,这将需要一个不同的程序:

Reading your question again, I realized that there may be another way to interpret your question. Perhaps you meant in index order where it's the .index data right next to the .name, not the index key on the tasks object. If so, that would take a different routine:

var sorted = [];
var i;
for (i in tasks) {
    sorted.push(tasks[i]);   // collect items from tasks into a sortable array
}
sorted.sort(function(a,b) {return(a.index - b.index);});  // sort the array in numeric order by embedded index
for (i = 0; i < sorted.length; i++) {
    console.log(sorted[i].name);
}

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

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