Skip to content
Advertisement

Convert an array to a list using jQuery

Got a challenge to convert a two dimensional array to a html list. the array is like

JavaScript

The structure of the nested array item is id, textOfLink, parent. parent 0 means top level, parent 3 means the item is under another list item with id of 3. the target output will a list in html like

JavaScript

please note the array is not limited to 3 items, it is dynamic. any idea how to do it in jQuery?

Advertisement

Answer

http://jsfiddle.net/f9wtu/1/

Here’s my version:

JavaScript

Why this is a good approach:

  • Everything is wrapped in a function -> reusable, clean, easy to maintain, no global variables are added exception functionName
  • You are getting what you want as an output (jQuery Element) for your input (data array)
  • If you look at my code, you can easily read and follow what I am each line.
  • Clean code
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement