Custom javascript object sort and maintain index association
The object
var obj = {
uniquestring1:
{
obj1: 'content',
obj2: 'content'
},
uniquestring2:
{
obj1: 'conte开发者_开发百科nt'
}
}
So i need to sort the object by number of the elements contained by the first parent element. The use of .sort function is not a sollution for me because i need to maintain the index assosiaction which array's dont keep.
The result should be:
var obj = {
uniquestring2:
{
obj1: 'content'
},
uniquestring1:
{
obj1: 'content',
obj2: 'content'
}
}
Javscript objects don't have a sort order so they can't be sorted. To sort, you must have an array somewhere and I see no array in your code.
Object keys have no defined order.
- If you only need ordered access, use an array.
- If you only need keyed access, use an object.
- If you need access by both, you can use a parallel array, but this is a pain unless the data is not changing.
You could do a one-time creation of a parallel array that contained key references in sorted order like this:
var obj = {
uniquestring1:
{
obj1: 'content',
obj2: 'content'
},
uniquestring2:
{
obj1: 'content'
}
}
var objOrder = []; // sorted arrays that contains first level keys into obj
var num;
for (var i in obj) {
objOrder.push(i); // get all keys into the array
num = 0;
for (var j in obj[i]) {
++num; // count items in each key object
}
obj[i].keyCnt = num; // save this for later sorting purposes
}
// now sort the parallel array by keyCnt
objOrder.sort(function(a, b) {
return(obj[a].keyCnt - obj[b].keyCnt);
});
Then, to traverse the keys in sorted order, you would do it like this:
for (var i = 0; i < sortedOrder.length; i++ ) {
var item = obj[sortedOrder[i]];
// do something with item here
}
obj
is a hash not an array, so you can't sort it. For example, obj[0]; // is undefined
. Now if you had this:
var obj = {
uniquestring1:
{
obj1: 'content',
obj2: 'content'
},
uniquestring2:
{
obj1: 'content'
}
};
var arr = [],
for(var i in obj) {
arr.push(obj[i]);
}
arr.sort(function (a, b) {
return Object.keys(a).length - Object.keys(b).length;
})
Then that sort would work, with Object.keys
精彩评论