admin管理员组

文章数量:1389925

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'],
               ['edy', '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='edy'>edy</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 ?

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'],
               ['edy', '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='edy'>edy</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 ?

Share Improve this question edited Jan 10, 2015 at 4:32 user3191304 asked Jan 10, 2015 at 4:22 user3191304user3191304 2213 silver badges8 bronze badges 4
  • 3 Have you tried using a templating engine? – thefourtheye 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 ;-) – Mr. Polywhirl 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. – musicfuel Commented Jan 10, 2015 at 4:27
  • This array es 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 – user3191304 Commented Jan 10, 2015 at 4:31
Add a ment  | 

2 Answers 2

Reset to default 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' : "edy",
            'text' : "edy"
        }]
    },{
        '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'],
    ['edy', 'movies'],    
    ['puppet', 'theater'], 
];
               
var myObject = {
    'id' : "activity",
    'text' : "activity",
    'children' : [{
        'id' : "movies",
        'text' : "movies",
        'children' : [{
            'id' : "drama",
            'text' : "drama"

        },{
            'id' : "edy",
            'text' : "edy"
        }]
    },{
        '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>

The following snippet produces the expected result:

var myArray = [['activity', 'none'] , 
               ['movies', 'activity'],
               ['theater','activity'],
               ['drama', 'movies'],
               ['edy', '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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

本文标签: javascriptHow to create html from a two dimensional arrayStack Overflow