Dynamically create tree/nested JSON in JS - javascript

I'm planning to use Bootstrap Treeview where the Json is expected as below.
I need to dynamically add element to the "tree" based on respective input nodes
var tree = {};
tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1",
nodes : [
{
text : "GrandChild 3"
}
]
},
{
text: "Grandchild 2",
nodes : [
{
text : "GrandChild 4"
}
]
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
I've tried array.reduce() but couldn't make that work.
Looking for some approach

Manually, you could do this:
alert(tree[0].nodes[0].nodes[0].nodes[0].text);// alerts "GrandChild 3"
// add a node array:
tree[0].nodes[0].nodes[0].nodes[0].nodes = [{
text: "GrandChild NEW First"
}];
console.dir(tree);
Shows:
Array[5]0: Object nodes: Array[2]0: Object nodes: Array[2]0: Object nodes: Array[1]0: Object nodes: Array[1]0: Object text: "GrandChild NEW First" _proto__: Object length: 1__proto__: Array[0]text: "GrandChild 3" _proto__: Object length: 1
Do same to array 1:
Array[5]
1: Object
nodes : Array[1]
text : "Parent 2"
tree[1].nodes = [{
text: "GrandChild NEW Second"
}];
Now you just need code to determine the depth of nodes and what to add (node or text or both) at that point.
EDIT If it makes it clearer, the last addition can also be done thus:
Add a new node array, then push a value into that
tree[1].nodes = [];
tree[1].nodes.push({
text: "GrandChild NEW Second"
});

Edit 2 Link to Plunkr
Because of the nature of the snippet editor, the code below will not work on the snippet editor, but in order to ensure that the code does not magically vanish from plunkr, I've included it below. All you need to do is include jquery, bootstrap's css file, the treeview css, and treeview js file.
Some Issues
This may just be because I have never used treeview before in my life, but if you have opened up anything on the treeview or selected something, by adding in the new element you erase any of that action. Going through it quickly I didn't see a way to simply rebuild the node list (our tree variable) from the current states. I attempted to pass a pre-defined nodeId to see if we could make the changes directly onto the parent tree variable by using the get[State] commands but the id seems to be generated by the rendering aspect and is not carried over. (to clarify: I gave parent 1 a node id of 1, but when I called a couple of calls on it, I got that it's node id was 0)
The id convention seems to start at the first element (nodeId=0). It first then goes through the children (if any) of that node, incrementing the nodeId as it goes. Theoretically it would be a simple enough script to go back and enumerate the nodeId's manually so that you can make state changes so that the re-render looks the same as before, minus a newly appended node somewhere.
var tree = [{
text: "Parent 1",
nodes: [{
text: "Child 1",
nodes: [{
text: "Grandchild 1",
nodes: [{
text: "GrandChild 3"
}]
}, {
text: "Grandchild 2",
nodes: [{
text: "GrandChild 4"
}]
}]
}, {
text: "Child 2"
}]
}, {
text: "Parent 2"
}, {
text: "Parent 3"
}, {
text: "Parent 4"
}, {
text: "Parent 5"
}];
$(document).ready(function() {
$('#test').treeview({
data: tree
});
$('button.btn-primary').on('click', function() {
tree.push({
text: 'Parent ' + (tree.length + 1)
});
$('#test').treeview({
data: tree
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" />
<button class="btn btn-primary">Add Something</button>
<div id="test"></div>
Edit 1
After reading through the OP's question, I'm not 100% that the code below answers what they were looking for. I've asked for further clarification and will keep this answer here until I know more.
Original
I've got some code working on a code pen Here, but I will add it to the snippet editor.
var tree = [{
text: "Parent 1",
nodes: [{
text: "Child 1",
nodes: [{
text: "Grandchild 1",
nodes: [{
text: "GrandChild 3"
}]
}, {
text: "Grandchild 2",
nodes: [{
text: "GrandChild 4"
}]
}]
}, {
text: "Child 2"
}]
}, {
text: "Parent 2"
}, {
text: "Parent 3"
}, {
text: "Parent 4"
}, {
text: "Parent 5"
}];
function recursive_tree(data, tag, child_wrapper, level) {
var html = [];
//return html array;
level = level || 0;
child_wrapper = (child_wrapper != false) ? child_wrapper : 'ul';
$.each(data, function(i, obj) {
var el = $('<' + tag + '>');
el.html(obj.text);
if (obj.hasOwnProperty('nodes')) {
var wrapper = $('<' + child_wrapper + '>');
var els = recursive_tree(obj.nodes, tag, child_wrapper);
wrapper.append(els);
wrapper.appendTo(el);
}
html.push(el);
});
return html;
}
$(document).ready(function() {
var html = recursive_tree(tree, 'li', 'ul');
console.log(html);
$('#parent').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="parent"></ul>
What you're looking for is something called Recursion, and it's used a lot for things exactly like this. There tends to be a nested/self similar structure.
This should be enough for a basic idea of what to do, from here it's really change the html that gets created. I've never used Bootstrap Treeview, so I have no idea how it is setup HTML wise, otherwise I'd have this be a bit more exact.

Related

How to combine data from an array and object and put together into an array in JavaScript?

I have an array in which I have some string value holding the id along with answer selected and I have different object in which I have the detail about answer which is selected. The below array keep updated whenever we select an option from question.
arr = ["Q1A1", "Q2A3"]
assume Q1 is Question no. 1 and A1 is option selected from the question. And below I have an object for the corresponding Q1 which contained the detail about answers and this object also get change as we move over to Q2
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}
]
}
same way I have any another object for Q2 if we select the answer in Q1, now we have different object for Q2
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}
]
}
I need to lookup the object with the help of array which contain question and answer(eg, "Q1A1") with selected and need to find the text for answer selected i.e ("Yes") if u look into the above object for question 1. Hence I need put into the array like this way.
result = ["Q1_Yes","Q2_Test3"]
This code will help you to get those results.
let selected = ["Q1A1", "Q2A3"];
let QA = [
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}
]
},
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}
]
}
];
let all_answers = QA.reduce((allanswers,qa)=>(qa.answers.map(d=> allanswers[d.id]=[qa.id,d.text]),allanswers),{});
const result = selected.map(selected => all_answers[selected].join('_'))
console.log(result)

Get dinamically table header and dinamically add rows

I need to create a table with dynamically adding rows.
But I need to have a fixed table header that I got dynamically from JSON and table body also generated dynamically.
Here is JSON example
data = [
{
id: 0,
title: "control0",
text: "text 0"
},
{
id: 1,
title: "control1",
text: "text 1"
},
{
id: 2,
title: "control2",
text: "text 2"
},
{
id: 3,
title: "control3",
text: "text 3"
}
]
I try to create method, but I get new column instead of ROW
addRow(index, name) {
this.newDynamic = { id: index, name: name, text: "name" + index };
this.data.push(this.newDynamic);
return true;
}
Here is how now it is looking
But I need like this
When we click on button ADD ROW, I want to add new row but without title (like on picture), but update JSON with new object.
Here is stackblitz for example

How to change the image to text for Treantjs collapsible tree view?

I have to draw a representation of data using collapsible tree structure, i am using below example link for my purpose :
http://fperucic.github.io/treant-js/examples/collapsable/
But the problem i am facing is the above link had images at every node, i want to replace it with text which when i am doing it is generating the tree with correct branches but the text is not appearing.I am using my json like this:
{
"name":"sourcetable",
"children":[{"name":"MARD"},{"name":"MARD"},{"name":"MARD"},{"name":"MARD"}]
}
It comes something like this:
Let me know how i can show the name labels on the collapsible tree.
I think you are missing a bit:
nodeStructure: {
text: { name: "Parent node" },
children: [
{
text: { name: "First child" }
},
{
text: { name: "Second child" }
}
]
}
Taken from here:
http://fperucic.github.io/treant-js/
var simple_chart_config = {
chart: {
container: "#OrganiseChart-simple"
},
nodeStructure: {
text: { name: "Parent node" },
children: [
{
text: { name: "First child" }
},
{
[enter image description here][1]text: { name: "Second child" }
}
]
}
};
Demo Link:
https://fperucic.github.io/treant-js/examples/super-simple

AngularJS TreeView From JSON Object

I am newbie in AngularJS. I need to create a TreeView Structure From JSON Object.
My Return JSON Object is looks like below.
var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1},
{Name:'Item2', Childnodes : {
items = [
{Name:'Sub Item21', Childnodes : {}, id: 21}
{Name:'Sub Item22', Childnodes : {}, id: 22}
]
}, id: 2}];
Could you please help me to create a AngularJS Tree View.
Thanks in Advance.
You can create a Tree view using the Webix framework along with AngularJS.
https://github.com/TheAjinkya/webixTreeWithJava-
https://github.com/TheAjinkya/AngularWebixApplication
treedata = [{
id: "1",
value: "Book 1",
data: [{
id: "1.1",
value: "Part 1"
},
{
id: "1.2",
value: "Part 2"
}
]
},
{
id: "2",
value: "Book 2",
data: [{
id: "2.1",
value: "Part 1"
}]
}
];
tree = new webix.ui({
view: "tree"
});
tree.parse(treedata)
<script src="https://cdn.webix.com/edge/webix.js"></script>
<link href="https://cdn.webix.com/edge/webix.css" rel="stylesheet" />
Please use some sort of tree view module. They can make your life much easier. The only thing is that you need to re-format your data structure to the tree module style. You can write a service and do all re-formatting inside a service.
Some tree view module and plugin:
http://ngmodules.org/modules/angular.treeview
https://angular-ui-tree.github.io/angular-ui-tree/#/basic-example

How do I create a nested ordered list in HTML

What's the best way to create a nested list like this one from nested JSON objects (by list, I mean the < ol > tag or something custom with similar behaviour):
Parent 1
a. Sub 1
b. Sub 2
i.Sub Sub 1
ii.Sub Sub 2
c. Sub 3
Parent 2
As an example let's use a limit of maximum 3 "nesting levels" deep.
The JSON object that would generate this list would look like this:
[
{
"content": "Parent 1",
"children": [
{
"content": "Sub 1",
"children": [...]
},
{
"content": "Sub 2",
"children": [...]
}
]
},
{
"content": "Parent 2"
}
]
try this simplest approach
var obj = [{
"content": "Parent 1",
"children": [{
"content": "Sub 1",
"children": [{
"content": "sub sub 12"
}]
}, {
"content": "Sub 2",
"children": [{
"content": "sub sub 12"
}]
}]
}, {
"content": "Parent 2"
}];
var html = getListHTML(obj);
console.log( html );
$( "body" ).append( html );
function getListHTML(obj)
{
if ( !obj )
{
return "";
}
var html = "<ol>";
html += obj.map(function(innerObj) {
return "<li>" + innerObj.content + "</li>" + getListHTML(innerObj.children)
}).join("");
html += "</ol>";
return html;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can then give a different starting value (1 or a or i) based on the hierarchy level of li
This is a proposal with an iterative and recursive callback for Array#forEach and with proper element generating on the fly.
function getValues(el) {
var li = document.createElement('li'),
ol;
li.appendChild(document.createTextNode(el.content));
if (Array.isArray(el.children)) {
ol = document.createElement('ol');
el.children.forEach(getValues, ol);
li.appendChild(ol);
}
this.appendChild(li);
}
var data = [{ content: 'Parent 1', children: [{ content: 'Sub 1', children: [] }, { content: 'Sub 2', children: [{ content: 'Sub Sub 1' }, { content: 'Sub Sub 2' }, ] }, { content: 'Sub 3' }] }, { content: 'Parent 2' }],
ol = document.createElement('ol');
data.forEach(getValues, ol);
document.body.appendChild(ol);

Categories