[英]Sort javascript object with array as value
I have a Javascript Object in the format key:pair
where the pair
is an array containing 2 timestamp values. 我有一个格式为
key:pair
的Javascript对象,其中的pair
是包含2个时间戳值的数组。 I would like to sort this object so that the elements with the lowest numbers (earliest times) are displayed first. 我想对这个对象进行排序,以便首先显示具有最低编号(最早时间)的元素。
Here is an example of the object: {"21_2":[1409158800,1409160000],"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600]}
这是对象的示例:
{"21_2":[1409158800,1409160000],"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600]}
So in this case, I would want the final sorted object to read: 因此,在这种情况下,我希望将最终排序的对象读取为:
{"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600],"21_2":[1409158800,1409160000]}
Obviously the sort()
function will come into play here for the arrays, but how do I access those values inside the object? 显然,
sort()
函数将在此处为数组起作用,但是如何访问对象内部的那些值? Note the object key
isn't actually an integer because of the underscore. 注意,由于下划线,对象
key
实际上不是整数。
I have found this: Sort Complex Array of Arrays by value within but haven't been able to apply it to my situation. 我发现了这一点: 对数组中的复杂数组按值排序,但是还无法将其应用于我的情况。 Any help would be greatly appreciated.
任何帮助将不胜感激。
You could change the structure of your data like this: 您可以这样更改数据的结构:
var myArray = [{
"id" : "21_2" // id or whatever these are
"timeStamps" : [1409158800,1409160000]
}, {
"id" : "20_1"
"timeStamps" : [1409148000,1409149200]
}];
Then you could sort it by the regular array sort: 然后,您可以按照常规数组排序对其进行排序:
myArray.sort(function(a, b){
// however you want to compare them:
return a.timeStamps[0] - b.timeStamps[0];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.