Got a challenge to convert a two dimensional array to a html list. the array is like
JavaScript
x
2
1
var arr=[[1,"link1",3],[2,"link2",0],[3,"link3",2]]
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
JavaScript
1
4
1
link2
2
link3
3
link1
4
please note the array is not limited to 3 items, it is dynamic. any idea how to do it in jQuery?
Advertisement
Answer
Here’s my version:
JavaScript
1
51
51
1
var arr = [
2
[1, 'link1', 3],
3
[2, 'link2', 0],
4
[3, 'link3', 2]
5
];
6
7
function processData(list) {
8
var out = $('<ul>'), // or ol
9
idMap = {};
10
11
function get(id, text) {
12
var $el = idMap[id] || (idMap[id] = $('<li><a></a></li>'));
13
if (text) {
14
$el.children('a').text(text);
15
}
16
return $el;
17
}
18
19
function addChild($parent, $child) {
20
var $list = $parent.children('ul');
21
if (!$list.length) {
22
$list = $('<ul>').appendTo($parent);
23
}
24
$list.append($child);
25
}
26
27
var id,
28
text,
29
parentId,
30
$el;
31
32
for (var i = 0, l = list.length, item; i < l; i++) {
33
item = list[i];
34
id = item[0];
35
text = item[1];
36
parentId = item[2];
37
$el = get(id, text);
38
39
if (parentId) {
40
addChild(get(parentId), $el);
41
} else {
42
out.append($el);
43
}
44
}
45
46
return out;
47
}
48
49
50
$('#result').append(processData(arr));
51
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