How to sort a JSON in descending order?

4

I have a JSON value that I want to sort it in descending order (I think in the example you will understand).

Example:

var json = {
    'um': {
        'cont': '5'
    },
    'dois': {
        'cont': '10'
    }
    ...
};

So in this case, it should be ordered by the 'cont' value of each child of json .

In the example I used fixed values, but the code I'm going to use will have many more children in json and the cont values will be different too.

I think you can understand, but in the end the value should be: ['two', 'one'];

    
asked by anonymous 10.03.2014 / 17:50

2 answers

4

You can write a comparison function and pass it as a sort parameter of the array.

Example:

function comparer(a, b) {
    if (a.cont < b.cont)
        return -1;

    if (a.cont > b.cont)
        return 1;

    return 0;
}

arr.sort(comparer);

But in this case, json would have to be an array, rather than an object.

EDIT I made an example fiddle:

jsfiddle

Reference :

    
10.03.2014 / 17:54
1

I've already used this library to sort and also to filters, in javascript (json) arrays.

I just do not know if in your case you can change your object to an array, so yes it can be ordered.

If you can use an array, this is a great approach.

This library JLinq is very good, I have never had problems with it.

It works with several hierarchical levels of the JSON object, and already implements the comparer proposed by @Miguel.

    
10.03.2014 / 17:59