Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort (reverse) object of jsonparse?

I have object {"5":"5","4":"4","3":"3","2":"2","1":"1","-1":"P1",-2":"P2"} And use this function to parse elements:

function floormake(inobj) {
    var levels = '';
    var obj = JSON.parse(inobj);
    levels += '<ul>';
    Object.keys(obj).sort(-1).forEach(function (key) {
        levels += '<li>' + obj[key] + '</li>';
    });
    levels += '</ul>';
    return levels;
}

But result alway sorting by number: -1, -2, 1, 2 etc. BUT i need reverse sorting: 5, 4, 3, 2, 1, sort(-1) - doesn't work

like image 399
skywind Avatar asked Nov 14 '12 15:11

skywind


People also ask

How do you sort a JSON object in descending order?

The sort(), sorted(), and dumps() functions have been used here to sort the JSON object in ascending and descending order.

What does JSON parse() method do?

The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

How to return a JavaScript array from JSON parse?

When using the JSON.parse () on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object. Example. The JSON returned from the server is an array: var xmlhttp = new XMLHttpRequest ();

How to sort the values of a jsonobject in Java?

The constructor of a JSONObject can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get () and opt () methods or to convert values into a JSON text using the put () and toString () methods. In the below example, we can sort the values of a JSONObject in the descending order.

How do I parse a JSON file?

Example - Parsing JSON. Imagine we received this text from a web server: Use the JavaScript function JSON.parse() to convert text into a JavaScript object: var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); Make sure the text is written in JSON format, or else you will get a syntax error.

What is the difference between sort () and reverse () methods?

The sort method also checks by letter ordering. We can take the same above example and represent it in if-else a statement. This method reverses the array.As sort () method sorts array items to ascending order calling reverse () method on sort () like sort ().reverse () does the opposite of that it orders items in descending order.


1 Answers

Consider using .reverse() instead.

Object.keys(obj).sort().reverse().forEach( ....

Reverse documentation

Edit Note: As mentioned by @Shmiddty, the reverse() method does not actually sort. The array will need to be sorted then reversed.

like image 74
Joel Etherton Avatar answered Sep 23 '22 20:09

Joel Etherton