57

For example with have this code:

var json = {
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    },
    "user3" : {
        "id" : 1
    }
}

How can I sort this json to be like this -

var json = {
    "user3" : {
        "id" : 1
    },
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    }
}

I sorted the users with the IDs..
I don't know how to do this in javascript..

jordanhill123
  • 4,142
  • 2
  • 31
  • 40
julian
  • 4,634
  • 10
  • 42
  • 59
  • 3
    exact duplicate of [Sorting JavaScript Object by property value](http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value). Notice that you cannot sort them; objects are *unordered* key-value maps. – Bergi Jul 16 '13 at 19:06
  • it's not helping me.. i have different json..and the answer there doesn't work on my json for some reason.. – julian Jul 16 '13 at 19:11
  • 3
    Of course you need to adapt it… Did you understand how it works? If so and you had problems at adapting it, then please post your attempt. – Bergi Jul 16 '13 at 19:13
  • Convert the JSON to an array, sort the array, then convert back to JSON. Should work, but maybe you don't need to use JSON if you want to do this. – SharkofMirkwood Jul 16 '13 at 19:20
  • 3
    @SharkofMirkwood: There's no JSON involved, he's got plain object literals. And converting it back to an object will invalidate the sorting, so there's no point in doing it. – Bergi Jul 16 '13 at 19:21

4 Answers4

144

First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.

Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.

One option might be to make your data look like this:

var json = [{
    "name": "user1",
    "id": 3
}, {
    "name": "user2",
    "id": 6
}, {
    "name": "user3",
    "id": 1
}];

Now you have an array of objects, and we can sort it.

json.sort(function(a, b){
    return a.id - b.id;
});

The resulting array will look like:

[{
    "name": "user3",
    "id" : 1
}, {
    "name": "user1",
    "id" : 3
}, {
    "name": "user2",
    "id" : 6
}];
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
14

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}
Piranna
  • 1,697
  • 1
  • 14
  • 16
  • 1
    While this is interesting, it does not directly address the question posed. – Spencer Sullivan Nov 27 '18 at 19:11
  • 1
    I think, it answers it with a little bit of interpretation. You can sort whatever you want with that and don't have to provide an array. The interesting part is Object.keys( ... ).sort( ... ). – Solostaran14 Apr 08 '22 at 13:42
  • The answer of this specific question should be : `const sortedJson = Object.keys(json).sort( (a,b) => json[a].id - json[b].id ).reduce( (accu, val, index, array) => { accu[\`${val}\`] = json[val]; return accu; }, {});` – Solostaran14 Apr 08 '22 at 14:11
1

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}
Katana314
  • 8,429
  • 2
  • 28
  • 36
-5
if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
    return true;
}
jordanhill123
  • 4,142
  • 2
  • 31
  • 40