我有一个 json 对象,我想按升序对其进行排序
[{ d: "delte the text" }, { c: "copy the text" }]
密钥d
和c
是动态创建的,下次可能会更改。我怎么能把它分类成
[{ c: "copy the text" }, { d: "delte the text" }]
请帮助我如何做到这一点。谢谢!
我有一个 json 对象,我想按升序对其进行排序
[{ d: "delte the text" }, { c: "copy the text" }]
密钥d
和c
是动态创建的,下次可能会更改。我怎么能把它分类成
[{ c: "copy the text" }, { d: "delte the text" }]
请帮助我如何做到这一点。谢谢!
要对使用Array.sort
适当的比较函数作为参数的数组进行排序。比较函数接受两个参数,在这种情况下,它们应该是只有一个属性的对象。您想根据该属性的名称进行排序。
使用 获取对象的属性名最方便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;
}
它可以这样使用:
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;
});
请注意,这Object.keys
需要相当现代的浏览器(特别是 IE 版本至少为 9);否则你需要写这样的东西:
var keyX, keyY, name;
for (name in x) { keyX = name; break; }
for (name in y) { keyY = name; break; }