如何在jQuery中对JSON对象进行排序 [英] How to sort json object in jquery
本文介绍了如何在jQuery中对JSON对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON对象,如:
I have a JSON object like:
{
"resp" : [
{
"name" : "s"
},
{
"name" : "c"
},
{
"name" : "f"
}
]
}
在这里,我想按name
值按字母顺序对对象进行排序.
因此,它应该成为此对象:
Here, I want to sort the object by name
values in alphabetical order.
So, it should become this object:
{
"resp" : [
{
"name" : "c"
},
{
"name" : "f"
},
{
"name" : "s"
}
]
}
如何实现?
推荐答案
您应在JSON序列化之前对JavaScript对象中的数组进行排序.序列化的JavaScript对象不过是一个字符串,因此不应进行排序.看看这个:
You should sort the array inside the JavaScript object prior to the JSON serialization. A serialized JavaScript object is nothing more than a string and therefore shouldn't be sorted. Take a look at this:
var obj = {
rest: [
{ name: "s" },
{ name: "c" },
{ name: "f" }
]
};
function compare(a, b) {
if (a.name< b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
obj.rest.sort(compare);
JSON.stringify(obj)
这篇关于如何在jQuery中对JSON对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文