简体   繁体   中英

How to sort javascript object which contains arrays?

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]};

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM