将对象文字转换为排序的数组 [英] Converting an object literal to a sorted Array
问题描述
我有一个对象文字,其中其键的值是更多对象,内部对象的键之一称为等级"-并具有浮点值.我想将对象文字转换为内部对象的数组,并按"rank"的值排序.
I have an object literal, where the values of its key are more objects, and one of the keys of the inner objects is named "rank" - and has an floating point value. I want to convert the object literal to an array of the inner objects, sorted by the value of "rank".
输入对象:
{
452:{
bla:123,
dff:233,
rank:2
},
234:{
bla:123,
dff:233,
rank:1
}
}
输出数组:
[
{ bla:123, dff:233, rank:1},
{ bla:123, dff:233, rank:2 }
]
推荐答案
示例:
var data = {
foo: {
rank: 5
},
bar: {
rank: 2
},
baz: {
rank: 8
}
};
JavaScript:
Javascript:
var mappedHash = Object.keys( data ).sort(function( a, b ) {
return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
return data[ sortedKey ];
});
首先将内部对象按sort
的值赋予sort
,然后将包含对象的map
放入 Array .
That would first sort
the inner objects by the value of obj.rank
and after that map
the containing objects into an Array.
结果:[{rank: 2}, {rank: 5}, {rank: 8}]
参考: > ,Array.prototype.map
Reference: Object.keys
, Array.prototype.sort
, Array.prototype.map
上面的代码包含ECMAscript 262第5版代码,该代码在所有现代浏览器中都可用.如果还想支持旧版浏览器,则需要包括各种ES5-Shim库之一.
这篇关于将对象文字转换为排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!