Skip to content
Advertisement

Keep the sort order

I have a object with that values :

category_list = {
 "1000":{
     "name":"Cars",
     "order":"1",
     "level": "2"
  },
 "2010":{
     "name":"Houses",
     "order":"2",
     "level": "2"
  },
 "1030":{
        "name":"Cars",
        "order":"3",
        "level": "2"
     }
  }

And when I would like to show it Chrome reorders it based on the Index :

It becomes :

    category_list = {
 "1000":{
     "name":"Cars",
     "order":"1",
     "level": "2"
  },
  "1030":{
        "name":"Cars",
        "order":"3",
        "level": "2"
  },
  "2010":{
     "name":"Houses",
     "order":"2",
     "level": "2"
  }
 }

I wish to keep the order as it was when pushing! or reorder based on field “order”

Can someone please help with that?

Advertisement

Answer

JavaScript objects are by definition unordered.

If you need an ordered list, you should use an array (of objects) instead, e.g.:

var objs = [
    {
        "key": 1000,
        "name":"Cars",
        "order": 1,
        "level": 2
    }, ...
];

objs.sort(function(a, b) {
    return a.order - b.order;
});

NB: for numeric properties use numeric types.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement