使用新密钥重新排序JSON

时间:2012-12-01 02:45:12

标签: javascript json

我有一个从休息服务返回的大型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函数来完成此任务吗?

3 个答案:

答案 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)

您也可以使用jquery

中的这个插件

http://archive.plugins.jquery.com/project/sort

$(dataSet).sort("Time", "asc");