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?

2

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.