JavaScript的:分类收集,这是不是一个数组 [英] JavaScript: sorting collection, which is not an array

查看:104
本文介绍了JavaScript的:分类收集,这是不是一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对象在JavaScript中的集合是这样的:

I have a collection of objects in JavaScript like this:


Object collection = new Object();
collection[123] = new Item(); //another object
collection[425] = new Item();
collection[2134] = new Item();
//etc. etc.

//TODO: sort items

我想根据收集的项目对象的属性这个集合进行排序。有一个在JS数组良好内置排序功能,所以我的第一个想法是修改code从动地:

I would like to sort this collection according to the properties of the Item objects in collection. There is good built-in sort function in JS Array, so my first idea was to modify the code followingly:


Object collection = new Array();
collection[123] = new Item(); //another object
collection[425] = new Item();
collection[2134] = new Item();
//etc. etc.

collection.sort(comparisonFunction); //where comparisonfunction handles the sorting logic

现在的收集是很好的分类 - 但是,我无法访问使用属性,这是我用来设置他们的项目,即

Now the collection is nicely sorted - however, I cannot access the items using the property, which I used to set them, i.e.


collection[2134]

是空的,因为JS数组不包含很多内容(即使它会,结果就不会如预期)

is null, because the JS array does not contain that many elements (and even if it would, the result would not be as expected)

我需要的是


  • 要访问集合元素直接与我设置它们数值属性的能力(这已经是给定的,当不使用JS数组)

  • 要在项目集合中的排序能力

编辑:对象并不需要表现得像一个数组,它不是自然的数组。我需要的是pretty接近的Java TreeMap的 - 的集合,它保持一特定的顺序,并且这也是一个地图。或以另一种方式解释,我需要一个普通的旧JavaScript对象(其中一些人知道的关联数组),其包含的用户创建的元素进行排序。

the object does not need to behave like an array and it is not an array of nature. What I need is pretty close to Java TreeMap - a collection, which maintains a specific order, and which is also a map. Or explained in another way, I need a plain old JavaScript object (which some people know as "associative array") whose contained user-created elements can be sorted.

编辑2:我结束了使用的解决方案是阿纳托利的,稍加修改。基本上我创建一个数组,在那里我复制收藏和两个对象(数组和集合)映射到同时获得的好处。同时感谢Roatin马斯为指出迭代对象不能保证在任何类型的顺序发生(修改阿纳托利的解决方案时,我没有考虑这一点)。

Edit 2: the solution I ended up using is Anatoliy's, slightly modified. Basically I create an array, where I duplicate the "collection" and map the two objects (array and collection) to get the benefits of both. Also thanks to Roatin Marth for pointing out that iterating objects are not guaranteed to happen in any kind of order (I did consider this when modifying Anatoliy's solution).

推荐答案

下面是未经考验code(只是想法):

Here is the untested code (just idea):

var arr = [];
for (var i in collection) {
    collection[i].index = i;
    arr.push(collection[i]);
}
arr.sort(f);
var sorted_collection = {};
for (var j in arr) {
    sorted_collection[arr[j].index] = arr[j];
}

这篇关于JavaScript的:分类收集,这是不是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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