I have a JSON object like:
{
"resp" : [
{
"name" : "s"
},
{
"name" : "c"
},
{
"name" : "f"
}
]
}
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"
}
]
}
How how can I implement it?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.