简体   繁体   English

如何使用以下格式在javascript或jquery中对JSON对象进行排序

[英]How to sort a JSON object in javascript or jquery with the following format

"attributes": [
    "BytesServed",
    "Duration",
    "UniqueIPAddresses",
    "StopEvents",
],
"rows": [
    [
        "12118931578714",
        "160557966.305",
        "372",
        "193381",
    ],
    [

        "248313315029",
        "4628315.959",
        "350",
        "27352",

    ],
]

I have 2 arrays, where the first array has keys and the second array is a multi-dimensional array with values. 我有2个数组,其中第一个数组具有键,第二个数组是具有值的多维数组。

Is there any pre-defined function in Javascript or jQuery which will give me the values in descending order by passing a key? Javascript或jQuery中是否有任何预定义的函数,通过传递键,这些函数会按降序为我提供值?

I have a solution, but I feel that it is a more costly approach. 我有一个解决方案,但我认为这是一种成本更高的方法。 If anybody has better solution please let me know. 如果有人有更好的解决方案,请告诉我。

My current solution is -- get the index from the first array and loop through the second array and create a temporary array and then sort that temp array and use it. 我当前的解决方案是-从第一个数组获取索引并遍历第二个数组并创建一个临时数组,然后对该临时数组进行排序并使用它。

You don't need to create a temporary array. 您不需要创建一个临时数组。 Once you get the index of the attribute you're looking for (and for this example I shall assume it's in a variable called index and that the whole JSON object is in jsondata ), just a simple sort will do: 一旦获得了您要查找的属性的索引(在本示例中,我将假定它在名为index的变量中,并且整个JSON对象在jsondata ),只需执行一个简单的sort

jsondata.rows.sort(function(a,b) {
    return a[index]-b[index];
});

And there you have your sorted array. 在那里,您有了排序的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM