2

My array has the pairs of child and parent elements . The first element of each subarray is a child , the second is the parent

var myArray = [['activity', 'none'] , 
               ['movies', 'activity'],
               ['theater','activity'],
               ['drama', 'movies'],
               ['comedy', 'movies'],    
               ['puppet', 'theater'], 
                    . . 
               ];

I need to create the following HTML dynamically:

<div id='activity'>activity

     <div id='movies'>movies
               <div id='drama'>drama</div>
               <div id='comedy'>comedy</div>  
     </div>

     <div id='theater'>
               <div id='puppet'>puppet</div>
     </div>

</div>

I tried to write a recursive function but everything messed up. Do I need a recursive function at all ?

4
  • 3
    Have you tried using a templating engine? Commented Jan 10, 2015 at 4:25
  • Could you provide us with an attempt? Assigning a variable is not really coding... You need to provide logic. You mention that you used a recursive function, please show us ;-) Commented Jan 10, 2015 at 4:26
  • 1
    Do you have control over the structure of the array you are using for data? If so, you can structure myArray differently to make understanding the relationships and rendering the HTML much easier. Commented Jan 10, 2015 at 4:27
  • This array comes from a database table. This is the tabular structure. THe first field is the child, the second field is the parent element. I need to convert this table into HTML. It's pretty straightforward to do this manually, but the table is huge Commented Jan 10, 2015 at 4:31

2 Answers 2

5

Instead of an Element - Parent relationship, why not try an object?

The following is vanilla JavaScript, no jQuery needed.

Edit: I am keeping my original answer in-tact but I you want a more robust solution, check my script at the bottom.

var myObject = {
    'id' : "activity",
    'text' : "activity",
    'children' : [{
        'id' : "movies",
        'text' : "movies",
        'children' : [{
            'id' : "drama",
            'text' : "drama"
        },{
            'id' : "comedy",
            'text' : "comedy"
        }]
    },{
        'id' : "theater",
        'text' : "theater",
        'children' : [{
            'id' : "puppet",
            'text' : "puppet"
        }]
    }]
}
var generateHTML = function(data, targetEle) {
    var node = document.createElement("div");
    if (data.id)   node.setAttribute("id", data.id);
    if (data.text) node.appendChild(document.createTextNode(data.text));
    targetEle.appendChild(node);  
    if (data.children) {
        data.children.forEach(function(child, index, siblings) {
            generateHTML(child, node); // Recursion...
        }, this);
    }
}
generateHTML(myObject, document.body);
div>div {
    margin-left: 2em;
}


Edit

I have created a script to convert the table to an object:

var myArray = [
    ['activity', 'none'] , 
    ['movies', 'activity'],
    ['theater','activity'],
    ['drama', 'movies'],
    ['comedy', 'movies'],    
    ['puppet', 'theater'], 
];
               
var myObject = {
    'id' : "activity",
    'text' : "activity",
    'children' : [{
        'id' : "movies",
        'text' : "movies",
        'children' : [{
            'id' : "drama",
            'text' : "drama"

        },{
            'id' : "comedy",
            'text' : "comedy"
        }]
    },{
        'id' : "theater",
        'text' : "theater",
        'children' : [{
            'id' : "puppet",
            'text' : "puppet"
        }]
    }]
};

var getById = function(id) {
    return document.getElementById(id);
};

var typeOf = function(obj) {
    return Object.prototype.toString.call(obj)
        .replace(/^\[object (.+)\]$/, "$1").toLowerCase();
}

// Converts a relatioship table to an object.
var tableToHierarchy = function(relationMatrix) {
    var generateRelationships = function(matrix) {
        var relationships = {};
        matrix.forEach(function(relationship, index, matrix) {
            var child = relationship[0];
            var parent = relationship[1];
            var children = relationships[parent] || [];
            children.push(child);
            relationships[parent] = children;
        }, this);
        return relationships;
    };
    var generateHierarchy = function(root, relationships) {
        var hierarchy = {};
        var children = relationships[root] || [];
        hierarchy.id = root;
        hierarchy.text = root;
        hierarchy.children = [];
        children.forEach(function(child, index, siblings) {
            hierarchy.children.push(generateHierarchy(child, relationships));
        });
        return hierarchy;
    };
    
    var root = relationMatrix[0][1]; // First record's parent.
    var relationships = generateRelationships(relationMatrix);
    return generateHierarchy(relationships[root], relationships);
};
    
var generateHTML = function(data, targetEle, includeLvl, idPrefix) {
    var generate = function(data, parent, level, prefix) {
        var node = document.createElement("div");
        if (data.id)    node.setAttribute("id", prefix + data.id);
        if (includeLvl) node.className = 'lvl-' + level;
        if (data.text)  node.appendChild(document.createTextNode(data.text));
        parent.appendChild(node);  
        if (data.children) {
            data.children.forEach(function(child, index, siblings) {
                generate(child, node, level+1); // Recursion...
            }, this);
        }
        return node;
    };
    switch(typeOf(data)) {
        case 'object':
            return generate(data, targetEle, 0, idPrefix);
        case 'array':
            return generate(tableToHierarchy(data), targetEle, 0, idPrefix);
    }
    return null;
};

generateHTML(myObject, getById('objTest'), true, 'obj_');
generateHTML(myArray,  getById('arrTest'), true, 'arr_');
div>div {
    margin-left: 2em;
}

.lvl-0 { color: #ff0000; }
.lvl-1 { color: #00ff00; }
.lvl-2 { color: #0000ff; }
<h2>Array</h2>
<div id="arrTest"></div>
<h2>Object</h2>
<div id="objTest"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

This is the best solution. +1 @user3191304 you should use this for your educational purposes
2

The following snippet produces the expected result:

var myArray = [['activity', 'none'] , 
               ['movies', 'activity'],
               ['theater','activity'],
               ['drama', 'movies'],
               ['comedy', 'movies'],    
               ['puppet', 'theater'], 
               ];

var nodes = {};
for (var i in myArray) {
    var child = myArray[i][0];
    var parent = myArray[i][1];
    var children = nodes[parent] || [];
    children.push(child);
    nodes[parent] = children;
}

var divFromNode = function(parent) {
    var div = $("<div id=" + parent + ">");
    var children = nodes[parent];
    div.text(parent);
    for (i in children) {
        var child = children[i];
        div.append(divFromNode(child));
    }
    return div;
}

$("body").append(divFromNode(nodes["none"][0]));
div>div {
    margin-left: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

1 Comment

I migrated your fiddle to here. I also added CSS because why not? :-p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.