Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] [Javascript] Shouldn't there be a sort option on objects



> toplevel.midlevel.dataIWantToSortBy
> 
> "midlevel" is just a number that I use to order the data when I display
> it. "dataIWantToSortBy" contains... uh... stuff. For now let's just say
> it contains letters for alphabetical sorting.
> 
> So What I want to do is turn this:
> 
> toplevel.1.dataIWantToSortBy.value = C
> toplevel.2.dataIWantToSortBy.value = A
> toplevel.3.dataIWantToSortBy.value = B
> 
> Into:
> 
> toplevel.1.dataIWantToSortBy.value = A
> toplevel.2.dataIWantToSortBy.value = B
> toplevel.3.dataIWantToSortBy.value = C

As you've realized you need to turn it into an array. As you've
described the second level in the hierarchy as "just a number", I assume
it can just as well be an array index. So, use this code to convert it
into an array:

 var d=[];
 for(var ix in toplevel)d.push(toplevel[ix]);


Then to sort it, you have to specify a function to describe how to do
the sorting:

 d.sort(function(x,y){
   var a=x.data.value;
   var b=y.data.value;
   if(a<b)return -1;
   if(a>b)return +1;
   return 0;
   });


[1] below shows my full test code, which uses the objectToString()
utility function from [2]. No need for that if you are using firebug or
similar.

Darren

[1]:
toplevel={
    1:{
        data:{
            value:'C'
            }
        },
    2:{
        data:{
            value:'A'
            }
        },
    3:{
        data:{
            value:'B'
            }
        },
    }

alert(objectToString(toplevel));

var d=[];
for(var ix in toplevel)d.push(toplevel[ix]);

alert(objectToString(d));

d.sort(function(x,y){
  var a=x.data.value;
  var b=y.data.value;
  if(a<b)return -1;
  if(a>b)return +1;
  return 0;
  });

alert(objectToString(d));



[2]:
 http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json



-- 
Darren Cook, Software Researcher/Developer

http://dcook.org/work/ (About me and my work)
http://dcook.org/blogs.html (My blogs and articles)


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links