简体   繁体   English

Json对象通过使用javascript升序排序

[英]Json object sort by ascending using javascript

I have a json object and i want to sort it by ascending order 我有一个json对象,我想按升序对它进行排序

  [{ d: "delte the text" }, { c: "copy the text" }]

The key d and c are dynamically created, next time may be changed. 密钥dc是动态创建的,下次可能会更改。 How I can sort this into 我如何将其分类

[{ c: "copy the text" }, { d: "delte the text" }]

Please help me how I can do this. 请帮我怎么做。 Thanks! 谢谢!

To sort an array you use Array.sort with an appropriate comparison function as an argument. 要对数组进行排序,请使用带有适当比较函数作为参数的Array.sort The comparison function accepts two arguments, which in this case are expected to be objects with just a single property. 比较函数接受两个参数,在这种情况下,它们应该是仅具有单个属性的对象。 You want to sort based on the name of that property. 您要基于该属性的名称进行排序。

Getting an object's property names is most convenient with Object.keys , so we have this comparison function: 使用Object.keys最方便地获取对象的属性名称,因此我们具有以下比较功能:

function(x, y) { 
    var keyX = Object.keys(x)[0], 
        keyY = Object.keys(y)[0]; 

    if (keyX == keyY) return 0; 
    return keyX < keyY ? -1 : 1;
}

It can be used like this: 可以这样使用:

var input = [{ d: "delete the text" }, { c: "copy the text" } ];
var sorted = input.sort(function(x, y) { 
    var keyX = Object.keys(x)[0], 
        keyY = Object.keys(y)[0]; 

    if (keyX == keyY) return 0; 
    return keyX < keyY ? -1 : 1;
});

See it in action . 看到它在行动

Note that Object.keys requires a reasonably modern browser (in particular, IE version at least 9); 请注意, Object.keys需要使用相当现代的浏览器(尤其是IE版本至少为9); otherwise you would need to write something such as this instead: 否则,您将需要编写如下内容:

var keyX, keyY, name;
for (name in x) { keyX = name; break; }
for (name in y) { keyY = name; break; }

See it in action . 看到它在行动

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

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