-1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Azzeddine
  • 176
  • 2
  • 9
  • Is category_list an object or an array? You say it's an object, but then you use the `array.push` terminology. Anyway, you can't reorder the properties of an object. – Andy Sep 17 '13 at 12:00

2 Answers2

3

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

JavaScript objects do not guarantee a specific order for their attributes. So the structure you'd like to have simply doesn't exist in JavaScript.

So with the native structures you can get either:

  • Array: Guaranteed order, but only accessing elements sequentially or by a numeric (0..n-1) index
  • Object: Arbitrary order, but you can access elements sequentially (again, arbitrary order) or using its key (which can be any string)

If you need both you either need to add an array that maps the order to the object keys, e.g. [1000, 2010, 1030] or store the data in an array and create a mapping like this: {1000: 0, 2010: 1, 1030: 2}.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636