In my database I store a number of “topics” and “examples”. Each example belongs to one topic.
I’d like show all the topics by name ASC in a tree component except for one topic (Topic C) which I always want on top. This may though come to change later and I’d rather not change the basic JSON output of topics and examples from the DB.
1) Does it seem reasonable to generate the “unordered list” structure client side (or should I, already in the json_encode() phase make sure the order is appropriate?) and
2) how would I, in that case, filter one specific topic node by name and put it first in the sequence?
- Topic C
- Example
- Example
- Topic A
- Example
- Example
- Topic B
- Example
- Example
Your questions are very difficult to answer without knowing exaclty the reasons you’re doing this!
Anyway, in attempting to answer,
1) :
If you are generating a list in HTML on the server anyway, and the order of the list doesn’t change, why do it with JSON & JavaScript? Use your server side tech to do this.
If the list will change and you want something in the UI on the client to manage the order of the list and you have accessibility considerations: create your list and your JSON using your server side tech, order both server side and then render your HTML list and pass your JSON to the client. This will make the list available to client (user) without JavaScript enabled and the ‘sortable list’ available to JavaScript enabled clients.
If you don’t have any concern for users without JavaScript AND the list needs to be reorderable then just pass your JSON data to your client and use JavaScript to render it and handle the reordering.
2) I’m assuming that each of your objects that you want to sort is in an array? If they are then I would use the Array.sort method : http://www.w3schools.com/jsref/jsref_sort.asp
Something like the following should give you an idea of how to go about doing this:
I’m not sure how cross browser it would be and obviously you’ll need to generate the list from the JSON but it should give you somewhere to start, you could make it all more generic and efficient of course!
Good luck.