Mailing List Archive
tlug.jp Mailing List tlug archive tlug 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
- Date: Tue, 08 Feb 2011 13:26:19 +0900
- From: Darren Cook <darren@example.com>
- Subject: Re: [tlug] [Javascript] Shouldn't there be a sort option on objects
- References: <4D4E75AB.5060703@example.com>
- User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101208 Thunderbird/3.1.7
> 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)
- References:
Home | Main Index | Thread Index
- Prev by Date: Re: [tlug] [Javascript] Shouldn't there be a sort option on objects
- Next by Date: Re: [tlug] Great Git resources
- Previous by thread: Re: [tlug] Are ordered hashes useful?
- Next by thread: [tlug] Importing WiFi equipment
- Index(es):
Home Page Mailing List Linux and Japan TLUG Members Links