0

I have an object called classes, which looks like this:

Object {d1: Array[6], a1: Array[6]};

I add a new array: classes.b1 = [{"id":1,"vprasan":true},{"id":2,"vprasan":true}]

How can I sort this object, so it looks like this: Object {a1: Array[6], b1: Array[6], d1: Array[6]};

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
AlesSvetina
  • 403
  • 3
  • 6
  • 19

3 Answers3

2

You can't. The order of properties in a JavaScript object is undefined.

Definition of an Object from ECMAScript Third Edition (pdf):

4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

yole
  • 92,896
  • 20
  • 260
  • 197
1

As noted in the other answer you cannot sort the object so it "looks" a particular way as an object is inherently un-ordered. However I'm interpreting your question a little more liberally; looks to me like you want to sort by object key, "a1", "b1", "d1" etc. It is easy enough to do so and then your can process your object based on the sorted keys:

var classes = {d1: ['item1'], a1: ['item1','item2']};
classes.b1 = ['item1', 'item2', 'item3'];

var keys = Object.keys(classes);
keys.sort();

for (var i=0, n=keys.length; i<n; i++) {
    console.log(keys[i]);
    console.log(classes[keys[i]].length);
}

OUTPUT:

a1
2
b1
3
d1
1
Dexygen
  • 12,287
  • 13
  • 80
  • 147
0

Yeah man, you gotta put that in an array if order is important:

var classes = [
    {name: 'a1', value: Array[6]},
    {name: 'b1', value: Array[6]},
    {name: 'd1', value: Array[6]}
];

Then look into this question for sorting it.

Javascript - sort objects in an array alphabetically on one property of the array

Community
  • 1
  • 1
MartyBoggs
  • 381
  • 2
  • 9