No, you can't do that. Your jsonObj is an *object*, not an array, so it has
no sort order.

If you want to be able to sort your object, it needs to be an array, e.g.

var jsonObj = [
        {
                "Name" : "B",
                "Position" : "Sr"
        },
        {
                "Name" : "S",
                "Position" : "Sr"
        },
        {
                "Name" : "A",
                "Position" : "Jr"
        }
];

That is something you can sort. You can use JavaScript's sort() method of
the Array object with a callback function that compares two elements as you
wish.

If you have a large number of elements in the array, a sort callback can
slow down sorting. Let me know if this is the case - I have a very fast
array sort method for just this situation. To late at night for me to post
it right now, but remind me tomorrow...

-Mike

> From: Arun Kumar
> 
> I have a JSON object (dynamically created) which is given below:
> 
> var jsonObj = {
>       1 : {
>               "Name" : "B",
>               "Position" : "Sr"
>       },
>       2 : {
>               "Name" : "S",
>               "Position" : "Sr"
>       },
>       3 : {
>               "Name" : "A",
>               "Position" : "Jr"
>       }
> };
> 
> In the above JSON object, keys can be strings also.
> 
> Is there anyway that I can sort this JSON object  based on these keys?
> 
> The output should be as below:
> 
> var jsonObj = {
>       2 : {
>               "Name" : "Sai",
>               "Position" : "Sr"
>       },
>       1 : {
>               "Name" : "Bhushan",
>               "Position" : "Sr"
>       },
>       3 : {
>               "Name" : "Arun",
>               "Position" : "Jr"
>       }
> };
> 

Reply via email to