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 bee this object:
{
"resp" : [
{
"name" : "c"
},
{
"name" : "f"
},
{
"name" : "s"
}
]
}
How how can I implement it?
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 bee this object:
{
"resp" : [
{
"name" : "c"
},
{
"name" : "f"
},
{
"name" : "s"
}
]
}
How how can I implement it?
Share Improve this question edited Jun 17, 2015 at 8:02 Yeldar Kurmangaliyev 34.3k13 gold badges64 silver badges104 bronze badges asked Jun 15, 2015 at 7:01 DeenDeen 6212 gold badges16 silver badges30 bronze badges 2- stackoverflow./questions/881510/sorting-json-by-values – Alex Coloma Commented Jun 15, 2015 at 7:10
- Hello! I have edited your code styling, added some explanations and relevant tags. Please, review the changes. – Yeldar Kurmangaliyev Commented Jun 17, 2015 at 8:02
1 Answer
Reset to default 6You 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 pare(a, b) {
if (a.name< b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
obj.rest.sort(pare);
JSON.stringify(obj)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744313268a4568053.html
评论列表(0条)