2

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?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
Deen
  • 611
  • 2
  • 16
  • 30

1 Answers1

6

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)
Dibran
  • 1,435
  • 16
  • 24