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

var arr=[[1,"link1",3],[2,"link2",0],[3,"link3",2]]

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

link2
  link3
    link1 

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:

var arr = [
    [1, 'link1', 3],
    [2, 'link2', 0],
    [3, 'link3', 2]
];

function processData(list) {
    var out = $('<ul>'), // or ol
        idMap = {};

    function get(id, text) {
        var $el = idMap[id] || (idMap[id] = $('<li><a></a></li>'));
        if (text) {
            $el.children('a').text(text);
        }
        return $el;
    }

    function addChild($parent, $child) {
        var $list = $parent.children('ul');
        if (!$list.length) {
            $list = $('<ul>').appendTo($parent);
        }
        $list.append($child);
    }

    var id,
    text,
    parentId,
    $el;

    for (var i = 0, l = list.length, item; i < l; i++) {
        item = list[i];
        id = item[0];
        text = item[1];
        parentId = item[2];
        $el = get(id, text);

        if (parentId) {
            addChild(get(parentId), $el);
        } else {
            out.append($el);
        }
    }

    return out;
}


$('#result').append(processData(arr));

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
Advertisement