Access json passing variable name as string - javascript

I've some json files included in the page like this:
<script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script>
<script type="text/javascript" language="javascript" src="json/divaniClassici.json"></script>
All of them having same structure, containing different elements:
var divaniModerni = {
"modelli": [
{
"nome": "California",
"num": "5",
},
{
"nome": "Terra",
"num": "6",
},
{
"nome": "Laura",
"num": "7",
},
{
"nome": "Nonstop",
"num": "11",
},
{
"nome": "Venere",
"num": "8",
},
{
"nome": "Comfort",
"num": "5",
},
{
"nome": "Infinity",
"num": "8",
},
]
}
I'm now able to parse the file like this:
$(divaniModerni.modelli).each(function(index, element){ (...) }
but it's possible to dinamically change the file to parse passing the name to a function, like this?
function show(category)
{
$(category.modelli).each(function(index, element){ (...) }
}
show(divaniModerni);
I've tried with:
$(window[category].modelli).each(function(index, element){ (...) }
but It's not working...
EDIT:
Inside the each I'm dinamically creating a row on a table, based on the selected json elements:
$(divaniModerni.modelli).each(function(index, element){
if (i == 1)
riga += "<tr>";
riga += "<td><figure><a class='anteprime' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + ".jpg'><img src='images/anteprima/divani/" + element.nome + ".jpg' alt='" + element.nome + "'></a><div class='descrizione'>" + element.nome;
if (element.num > 0)
{
for (j = 2; j <= element.num; j++)
{
riga += "<a style='display:none;' class='anteprime' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + j + ".jpg'><img src='images/anteprima/divani/" + element.nome + j + ".jpg' alt='" + element.nome + "'></a>";
}
}
riga += "</div></figure></td>";
if (i == categoria.modelli.length)
{
riga += "</tr>";
$('#mostra').append(riga);
}
else if (i % 4 == 0)
{
riga += "</tr>";
$('#mostra').append(riga);
riga = "<tr>";
}
i++
})

Pass in the object reference directly into the each statement to only iterate on that.
http://jsfiddle.net/b3zdahc0/
var divaniModerni = {
"modelli": [
{
"nome": "California",
"num": "5",
},
{
"nome": "Terra",
"num": "6",
},
{
"nome": "Laura",
"num": "7",
},
{
"nome": "Nonstop",
"num": "11",
},
{
"nome": "Venere",
"num": "8",
},
{
"nome": "Comfort",
"num": "5",
},
{
"nome": "Infinity",
"num": "8",
}
]
};
function show(category)
{
$.each(category.modelli, function(index, element) {
alert(index)
});
}
$("button").on("click", function(e) {
show(divaniModerni);
});

Related

How to retrieve array inside array in javascript?

Here is my Json array. I want to retrieve child arrays and I need to display all the invoices details under the project section. Please check the attached screenshot. In the screenshot you can see only last invoice details only displaying to all other projects. The last invoice number 1005 is showing for all. How can I show invoice details based on the project details?
When child row is empty,project details (parent) also not showing.Am getting projectinvoicesection: [] Array 0. I need to display project details and no record found in invoice section. But now am getting array zero.
[{
"parent": {
"project_ID": "1",
"project_title": "Network and Telephone Points",
"particulars": "Test Description",
"project_amount": "10000.00",
"type": "One Time",
},
"child": [{
"invoice_No": "1002",
"received_Amt": "0.00",
"invoice_amount": "472.50",
"proje_ID": "1",
"invoice_Date": "2021-08-31"
}]
},
{
"parent": {
"project_ID": "2",
"project_title": "Configuration and Programming",
"particulars": "test description",
"project_amount": "2000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1004",
"received_Amt": "0.00",
"invoice_amount": "245.70",
"proje_ID": "2",
"invoice_Date": "2021-08-30"
}]
},
{
"parent": {
"project_ID": "3",
"project_title": "Coffee ERP",
"particulars": "test",
"project_amount": "50000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1000",
"received_Amt": "0.00",
"invoice_amount": "1820.70",
"proje_ID": "3",
"invoice_Date": "2021-08-19"
},
{
"invoice_No": "1001",
"received_Amt": "0.00",
"invoice_amount": "1773.45",
"proje_ID": "3",
"invoice_Date": "2021-08-24"
}
]
},
{
"parent": {
"project_ID": "6",
"project_title": "sample project new design",
"particulars": "Test Project new",
"project_amount": "4000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1005",
"received_Amt": "0.00",
"invoice_amount": "283.50",
"proje_ID": "6",
"invoice_Date": "2021-08-21"
}]
}
]
I have tried this code below:
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i + 1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
//alert(t1)
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #337ab7;color: white;' class='accordion-toggle'><td>" + sl + "</td><td>" + t4 + "</td><td>" + t1 + "</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='border-collapse:collapse;'><thead><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
}
for (var property in object) {
//alert(object[property].invoice_No);
var t6 = format(object[property].invoice_Date);
var t7 = object[property].invoice_No;
var t8 = object[property].invoice_amount;
var t9 = object[property].received_Amt;
var t10 = object[property].proje_ID; //invoice table's project id
var trtoggle = "<tr><td>" + t6 + "</td><td>" + t7 + "</td><td>" + t8 + "</td><td class=''>" + t9 + "</td><td class=''><input type='checkbox' name='myTextEditBox' value='checked' /> checkbox</td></tr>";
$(".tableinvoice_proj").append(trtoggle);
}
Here is the screenshot
PHP MODAL:
public function list_all_projects_invoice($data) //project section display with ALL Category
{
$array_store = array();
foreach($this->one_allcategory($data) as $row) {
$child = $this->many_allcategory($row['project_ID']);
if($child) {
$return = array_merge(array("parent" => $row), array("child" =>$child));
array_push($array_store, $return);
}
}
return $array_store;
}
public function one_allcategory($data) {
$query = $this->db->select("*")
->where("comp_ID", $data)
->get("project_details")
->result_array();
return $query;
}
public function many_allcategory($id) {
$query = $this->db->select('invoice_No,received_Amt,invoice_amount,proje_ID,invoice_Date')
->where("proje_ID", $id)
->get("invoice_details")
->result_array();
return $query;
}
It's because you append trtoggle to .tableinvoice_proj without specifying the exact element with this class then trtoggle append to all of element with .tableinvoice_proj class.
According to the code you can try
$(".tableinvoice_proj").last().append(trtoggle);
instead of
$(".tableinvoice_proj").append(trtoggle);
new_data = new Object();
new_data.projectinvoicesection = [{
"parent": {
"project_ID": "1",
"project_title": "Network and Telephone Points",
"particulars": "Test Description",
"project_amount": "10000.00",
"type": "One Time",
},
"child": [{
"invoice_No": "1002",
"received_Amt": "0.00",
"invoice_amount": "472.50",
"proje_ID": "1",
"invoice_Date": "2021-08-31"
}]
},
{
"parent": {
"project_ID": "2",
"project_title": "Configuration and Programming",
"particulars": "test description",
"project_amount": "2000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1004",
"received_Amt": "0.00",
"invoice_amount": "245.70",
"proje_ID": "2",
"invoice_Date": "2021-08-30"
}]
},
{
"parent": {
"project_ID": "3",
"project_title": "Coffee ERP",
"particulars": "test",
"project_amount": "50000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1000",
"received_Amt": "0.00",
"invoice_amount": "1820.70",
"proje_ID": "3",
"invoice_Date": "2021-08-19"
},
{
"invoice_No": "1001",
"received_Amt": "0.00",
"invoice_amount": "1773.45",
"proje_ID": "3",
"invoice_Date": "2021-08-24"
}
]
},
{
"parent": {
"project_ID": "6",
"project_title": "sample project new design",
"particulars": "Test Project new",
"project_amount": "4000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1005",
"received_Amt": "0.00",
"invoice_amount": "283.50",
"proje_ID": "6",
"invoice_Date": "2021-08-21"
}]
},
{
"parent": {
"project_ID": "9",
"project_title": "TEST",
"particulars": "NO RESULT",
"project_amount": "0",
"type": "One Time",
"period_type": " ",
},
"child": []
}
]
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i + 1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
//alert(t1)
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #337ab7;color: white;' class='accordion-toggle'><td>" + sl + "</td><td>" + t4 + "</td><td>" + t1 + "</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='border-collapse:collapse;'><thead><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
if( !object || object.length < 1)
{
var trtoggle = `<tr ><td style='text-align:center;' colspan='5' > No records found!</td></tr>`;
} else
{
var trtoggle = '';
for ( var property in object ) {
//alert(object[property].invoice_No);
var t6 = object[property].invoice_Date;
var t7 = object[property].invoice_No;
var t8 = object[property].invoice_amount;
var t9 = object[property].received_Amt;
var t10 = object[property].proje_ID; //invoice table's project id
trtoggle += "<tr><td>" + t6 + "</td><td>" + t7 + "</td><td>" + t8 + "</td><td class=''>" + t9 + "</td><td class=''><input type='checkbox' name='myTextEditBox' value='checked' /> checkbox</td></tr>";
}
}
$(".tableinvoice_proj").last().append(trtoggle);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableproject">
</table>
Your second for loop needs to be inside of the first for loop (nested):
//You have
For(){
}
For(){
}
//You need
For(){
For(){
}
}

Not getting the expected results from for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm having trouble with a if statement in a for loop where the items are not fitting under the h1 like i would of expected it's almost like the if is been missed the first go and that messes things up
Here is some example code and the jsfiddle to go with it http://jsfiddle.net/xpvt214o/714036/
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = h1marker + contentNow + content
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>
There is no problem with your if-statement at all. Your code at this part
content = h1marker + contentNow + content
Puts the new content IN FRONT of the old, therefore your second entry for each date is above the header "30".
Change it to content = content + h1marker + contentNow like in the following snippet:
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = content + h1marker + contentNow
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>

How to delete a row from json while getting a json using javascript

I am trying to get a json .Which row has a null value I want to delete it using javascript.
Suppose my json is like
[{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}, {
"chkey": null,
"list": null
}]
}]
If chkey and chvalue is null then row will be deleted.
Expected result is
[{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}]
}]
Could you please help me to resolve this problem.
Assuming you've serialised your JSON into a JavaScript object:
var my_array = [{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}, {
"chkey": null,
"list": null
}]
}];
document.write("<pre>" + JSON.stringify(my_array) + "</pre>");
for (var i = 0; i < my_array.length; i += 1) {
var rows = my_array[i].channelGraph;
for (var j = 0; j < rows.length; j += 1) {
if (rows[j].chkey === null && rows[j].chkey === null) {
rows.splice(j, 1); // Removes one row at index j
j -= 1; // Avoid skipping a row -
// we want the next row to be next.
}
}
}
document.write("<pre>" + JSON.stringify(my_array) + "</pre>");
Try this :
var obj = [{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}, {
"chkey": null,
"list": null
}]
}];
obj[0].channelGraph.filter((item, index) => {
(!item.chkey && !item.list) ? obj[0].channelGraph.splice(index, 1) : '';
});
console.log(obj);

Jquery multiply input number value and Json data

I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/

String not being appended in function

I am trying to parse a JSON and build a HTML string to append to the DOM but no matter what I do the string is only returning the first element in the JSON.
Here's the js:
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
var test_html = "<ul>",
buildNavHelper = function(curNode){
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
};
buildNavHelper(menu_json);
test_html += "</ul>";
$('#thing').append(test_html);
Heres a fiddle
https://jsfiddle.net/w734bvw7/
buildNavHelper() has no return statement, so there's nothing coming back from _.map(). The outer test_html isn't in scope. Try this:
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
test_html = "<ul>" + buildNavHelper(menu_json) + "</ul>";
Note the addition of .join() to avoid having commas in your output.
Also, there's no need to use underscore here; Array.map() is native Javascript.
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + curNode.children.map(buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
https://jsfiddle.net/w734bvw7/3/
buildNavHelper = function(curNode){
var test_html = "<ul>";
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
test_html += "</ul>";
return test_html;
};
$('#thing').append(buildNavHelper(menu_json));
Building the list using HTML strings can produce HTML injection. I recommend DOM methods instead:
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
document.querySelector('#thing').appendChild(buildNavHelper([menu_json]));
<div id="thing"></div>

Categories

Resources