我有一个从休息服务返回的大型JSON,我需要先对它进行排序才能使用它。
示例行:
[{"Time":"1354233600000","Name":"NAN","TagValue":"0","TagValue2":"0"},
{"Time":"1354234500000","Name":"NAN","TagValue":"0","TagValue2":"0.0020288255172466159"},
{"Time":"1354235400000","Name":"NAN","TagValue":"0","TagValue2":"0.0022446943714048121"},
{"Time":"1354236300000","Name":"NAN","TagValue":"0","TagValue2":"0.00014998416164500384"},
{"Time":"1354237200000","Name":"NAN","TagValue":"0","TagValue2":"0"},
{"Time":"1354238100000","Name":"NAN","TagValue":"0","TagValue2":"0.00015631034628383933"},
{"Time":"1354239000000","Name":"NAN","TagValue":"0","TagValue2":"1.1165024734559951E-05"}
大约有2000条这样的线。我想按时间对它们进行排序,得到类似的结果:
var restData = { "1354234500000":[
{"Name":"NaN",
"TagValue":"0",
"TagValue2":"someFloat"}
{"Name:"NAN,
"TagValue":"0",
"TagVale":"0"}
],
"aNewUnixTimeStamp":[
{..........}
]};
我可以使用一些神奇的javascript函数来完成此任务吗?
答案 0 :(得分:1)
假设您的对象整齐地排列在一个数组中,您只需调用
即可bigArray.sort(function(a,b) {return a.Time < b.Time ? -1 : 1})
答案 1 :(得分:1)
var myarray = [{"Time":"1354233600000","Name":"NAN","TagValue":"0","TagValue2":"0"},
{"Time":"1354234500000","Name":"NAN","TagValue":"0","TagValue2":"0.0020288255172466159"},
{"Time":"1354235400000","Name":"NAN","TagValue":"0","TagValue2":"0.0022446943714048121"},
{"Time":"1354236300000","Name":"NAN","TagValue":"0","TagValue2":"0.00014998416164500384"},
{"Time":"1354237200000","Name":"NAN","TagValue":"0","TagValue2":"0"},
{"Time":"1354238100000","Name":"NAN","TagValue":"0","TagValue2":"0.00015631034628383933"},
{"Time":"1354239000000","Name":"NAN","TagValue":"0","TagValue2":"1.1165024734559951E-05"}
var result = myarray.reduce(function(res, obj) {
if (res.hasOwnProperty(obj.Time) === false) {
res[obj.Time] = [];
}
res[obj.Time].push(obj);
delete obj.Time;
return res;
}, {});
您应该知道,由于结果是使用时间戳作为对象的键,因此您无法对它们进行排序,因为对象没有已定义的顺序。
同样.reduce()
将需要旧版浏览器的垫片。您可以使用provided by MDN。
答案 2 :(得分:0)