Nested JSON to Numbered HTML Table using Javascript - javascript

I'm trying to generate HTML table from JSON
The JSON provided is deeply nested. With the help of this thread How do I loop through deeply nested properties of a JavaScript object?, I am able to get the values of the JSON but I am confused on how to generate the HTML table
var districts = {
"district": [{
"ration": 4,
"states": [{
"name": "Louisiana",
"population": 42383,
"cities": [{
"name": "Cavalero"
}]
}]
}, {
"ration": 1,
"states": [{
"name": "Colorado",
"population": 980,
"cities": []
}, {
"name": "Arkansas",
"population": 58998,
"cities": []
}, {
"name": "Illinois",
"population": 59333,
"cities": [{
"name": "Kenwood"
}]
}]
}, {
"ration": 2,
"states": [{
"name": "Washington",
"population": 83984,
"cities": [{
"name": "Conestoga"
}, {
"name": "Whitehaven"
}, {
"name": "Dellview"
}]
}, {
"name": "West Virginia",
"population": 38034,
"cities": []
}]
}]
};
var i, district, j, states, k, cities;
for (i = 0; i < districts.district.length; i++) {
district = districts.district[i];
print(i + 1, ". District", i + 1, "consists of following states", "--- ration", district.ration);
for (j = 0; j < district.states.length; j++) {
states = district.states[j];
var said = (states.cities.length > 0) ? ("consists of following cities") : ("");
print(i + 1, ".", j + 1, states.name, said, "--- population", states.population);
for (k = 0; k < states.cities.length; k++) {
cities = states.cities[k];
print(" ", i + 1, ".", j + 1, ".", k + 1, cities.name);
}
}
}
Run this on Ideone
Any pointers/help/suggestions appreciated

You will need to generate a table, like this:
var districts = {
"district": [{
"ration": 4,
"states": [{
"name": "Louisiana",
"population": 42383,
"cities": [{
"name": "Cavalero"
}]
}]
}, {
"ration": 1,
"states": [{
"name": "Colorado",
"population": 980,
"cities": []
}, {
"name": "Arkansas",
"population": 58998,
"cities": []
}, {
"name": "Illinois",
"population": 59333,
"cities": [{
"name": "Kenwood"
}]
}]
}, {
"ration": 2,
"states": [{
"name": "Washington",
"population": 83984,
"cities": [{
"name": "Conestoga"
}, {
"name": "Whitehaven"
}, {
"name": "Dellview"
}]
}, {
"name": "West Virginia",
"population": 38034,
"cities": []
}]
}]
};
//Start of the table, including header
var table = '<table><thead><tr><th>Num</th><th>District</th><th>Population</th><th>Ration</th></tr></thead><tbody>';
//Num
for (var i = 0; i < districts.district.length; i++) {
//District
var district = districts.district[i];
//First row
table += '<tr><td>' + (i + 1) + '</td><td>District ' + district.ration + ' consists of the following states:</td><td></td><td>' + district.ration + '</td></tr>';
//States
var states = district.states;
for (var j = 0; j < states.length; j++) {
table += '<tr><td></td><td>' + (i + 1) + '.' + (j + 1) + ' ' + states[j] + ((states[j].cities && states[j].cities.length) ? ' consists of following cities:' : '') + '</td><td>' + states[j].population + '</td><td></td></tr>';
//Cities
if (states[j].cities) {
for (var k = 0; k < states[j].cities; k++) {
table += '<tr><td></td><td>' + (i + 1) + '.' + (j + 1) + '.' + (k + 1) + ' ' + states[j].cities[k].name + '</td><td></td><td></td></tr>';
}
}
}
}
//End of the table
table += '</tbody></table>';
and then add table somewhere into your html.

if you want to generate the desired output as on that link, you can use
<ol>
<li></li>
<li>
<ol><li></li></ol>
<li>
</ol>
instead of table. generate it using javascript. you can use below code to generate your ordered list which should be inserted on the main ordered list tag.
var district = districts.district;
function generateCities(cities){
cities.map((city) => {
return (
"<li>"+ city.name + "</li>"
)
})
}
function generateStates(states, generateCities){
states.map((stat) => {
return (
"<li>"+stat.name + " consists of following cities --- population " + stat.population + "</li>"
+"<ol>" + generateCities(stat.cities) + "</ol>"
)
});
}
function generateMyHtml(district, generateStates){
district.map((dist, index) => {
return (
"<li> District "+ index + "consists of following states --- ration " + dist.ration + "</li>"
+"<ol>" + generateStates(dist.states) + "</ol>"
)
});
};
hope this is helpful

Related

Can't seem to reference data in a complex JSON file, probably just my syntax

I am a noob so please forgive me. I have the following JSON file:
`{ "Series": {"Next":
[ { "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"},
{ "Name": "Crisps", "Price" : 3, "Location": "the Snack isle"},
{ "Name": "Pizza", "Price" : 4, "Location": "Refrigerated foods"},
{ "Name": "Chocolate", "Price" : 1.50, "Location": "the Snack isle"},
{ "Name": "Self-raising flour", "Price" : 1.50, "Location": "Home baking"},
{ "Name": "Ground almonds", "Price" : 3, "Location": "Home baking"} ]}`
I'm trying to reference the Name, Location and Price but it's now working. Here is the JavaScript code I am using:
.then(function(json) {
for(var i = 0; i < json.Next.length; i++) {
var listItem = document.createElement('li_prod');
listItem.innerHTML = '<strong_prod>' + json.Next[i].Name + '</strong_prod>';
listItem.innerHTML +=' can be found in ' + json.Next[i].Location + '.';
listItem.innerHTML +=' Cost: <strong_prod>£' + json.Next[i].Price + '</strong_prod>';
myList.appendChild(listItem);
}
that code is not picking up the Name, Location or price. How can I reference the data? Something like json.Series.Next[i].Name?
with the structure of your object it's more json.Series.Next instead of json.Next
var json = {
"Series": {
"Next":
[{
"Name": "Cheese",
"Price": 2.50,
"Location": "Refrigerated foods"
},
{
"Name": "Crisps",
"Price": 3,
"Location": "the Snack isle"
},
{
"Name": "Pizza",
"Price": 4,
"Location": "Refrigerated foods"
},
{
"Name": "Chocolate",
"Price": 1.50,
"Location": "the Snack isle"
},
{
"Name": "Self-raising flour",
"Price": 1.50,
"Location": "Home baking"
},
{
"Name": "Ground almonds",
"Price": 3,
"Location": "Home baking"
}
]
}
}
var myList = document.getElementById('my-list');
for (var i = 0; i < json.Series.Next.length; i++) {
var listItem = document.createElement('li_prod');
listItem.innerHTML = '<strong_prod>' + json.Series.Next[i].Name + '</strong_prod>';
listItem.innerHTML += ' can be found in ' + json.Series.Next[i].Location + '.';
listItem.innerHTML += ' Cost: <strong_prod>£' + json.Series.Next[i].Price + '</strong_prod>';
myList.appendChild(listItem);
}
<div id="my-list">
</div>

How to create dl tags and display data in it

I have a json data and i want to display it in dl tags and i want to create new dl tags every time i loop through the json data, but the output i got is the dl will be created and closed before the dt and dd which were suppose to be inide it is created, you can see in the fiddle below jsfiddle.net/buo28k1L/56/. Below is my code i added style to the dl to show where the dl is formed and you can see that the dt and dd are outside of the dl instead of being inside it.
HTML
<div id="content"></div>
CSS
dl {
border:1px solid red;
height: 100px;
width: 300px;
}
JS
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
// var d = $( document.createElement('dl') );
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
There is a mistake inside your first for loop.
try this one.
for (var i = 0; i < firstdata.length; i++) {
// var d = $( document.createElement('dl') );
//create an empty dl tag
var dl = $("<dl></dl>");
//append your dt
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dt>");
//append your all dd
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" +secdata[i][j].name + "</dd>");
}
}
//append each dl before starting new one.
content.append(dl);
}
You are using append() incorrectly. What you can do is first create a HTML string with dt and dd so that this can be then added to dl and then append this dl to div with id as content. For further verification of below snippet, you can use browser inspect element and you will see that the HTML is rendered as
<dl>
<dt href="67">Baby & Toddler Clothing </dt>
<dd href="572">Baby Clothing Accessories </dd>
<dd href="573">Baby Shoes</dd>
</dl>
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
// var d = $( document.createElement('dl') );
var dtHTML = "<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dt>";
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dtHTML += "<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>";
}
}
$("#content").append('<dl>'+dtHTML+'</dl>');
}
} else {
console.log('no item for this categories');
}
dl{
border:1px solid red;
height: 100px;
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
You can also do it with Javascript
if(data.length > 0) {
var content = document.getElementById('content');
firstdata = data[0];
secdata = data[1];
var dl = document.createElement('dl');
for (var i = 0; i < firstdata.length; i++) {
var dt = document.createElement('dt');
dt.href = firstdata[i].id;
dt.append(document.createTextNode(firstdata[i].name));
dl.append(dt);
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
var dd = document.createElement('dd');
dd.href = secdata[i][j].id;
dd.append(document.createTextNode(secdata[i][j].name));
dl.append(dd);
}
}
}
content.append(dl);
}
else
{
console.log('no item for this categories');
}
You can solve your problem in a much simpler way by using the template string (``) backticks.
Create your html structure using these backticks(``) and just append the content to the div
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
var dlList = data[0].map((dt, index) => {
var ddList = data[1][index].map(dd => {
return `<dd>${dd.name}</dd>`;
}).join('');
return `<dl>
<dt>${dt.name}</dt>
${ddList}
</dl>`;
}).join('');
content.append(dlList);
} else {
console.log('no item for this categories');
}
dl{
border:1px solid red;
height: 100px;
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

Getting specific value from object array for html injection

I'm trying to get a certain value from a Json file for html injection. The Json can have multiple arrays much more than in this example, but only the first array value of each array has certain value called title. Example json:
var placesdata= {
"Places": {
"Berlin": [
{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [
{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
I'm inserting all the values to HTML in a function that loops trough all of the arrays in the object. Here the problem is that I don't know how to insert the title value so that the HTML gets it. Tried numerous ways doing it but all failed. I'm trying to insert the title value at toimipistedata[key1][0].title:
function CreateAccordionTitles($container) {
for (var i = 0; i < Object.keys(placesdata).length; i++) {
var component =
'<div class="title">' +
'<i class="dropdown icon"></i>' +
placesdata[key1][0].title +
'</div>' +
'<div class="content styleSetSubAccordion">' +
'<div class="ui two column divided grid ' + Object.keys(placesdata)[i] + '\">' +
'</div>' +
'</div>'
if ($container.length) {
$container.append(component);
}
}
}
(The $container is an id/class for HTML element)
So how can I get the title value from the object arrays so that I can insert it with the HTML?
Tried to make a snippet about how it currently works and what needs to be changed in comments but failed something so it broke:
var placesdata= {
"Places": {
"Berlin": [
{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [
{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
function CreateTitles($container) {
for (var i = 0; i < Object.keys(placesdata).length; i++) {
var component =
'<li>' +
Object.keys(placesdata)[i] + //this needs to get the title value like this toimipistedata[key1][0].title
'<ul class="place ' + Object.keys(placesdata)[i] + '\">' +
'</ul>' +
'</li>'
if ($container.length) {
$container.append(component);
//CreateToimipisteContent(placesdata.Object.keys(placesdataa)[i], "." + Object.keys(placesdata)[i]); I need this to work
}
}
}
function CreateToimipisteContent(data, elementpos) {
for (var i = 0; i < data.length; i++) {
var dat = data;
var $txtp = $('<li>' + dat[i].location + '</li>').appendTo(elementpos);
$txtp.addClass(dat[i].buildings);
}
}
CreateTitles($("#Placement"));
CreateToimipisteContent(placesdata.Poliklinikat, ".Berlin"); // i dont want to use these like this they need to come form the CreateTitles function, these should be removed
CreateToimipisteContent(placesdata.Tutkimustoimenpiteet, ".Paris"); // i dont want to use these like this they need to come form the CreateTitles function, these should be removed
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="Placement"></ul>
<script src="jquery-3.3.1.min.js"></script>
</body>
</html>
You could use Array.prototype.find, which returns the first element that fulfils the supplied predicate.
I've got no idea what toimipistedata is so I'll give you as close an example as I can:
var title = placesdata.Places[city].find(x => x.title).title;
This works because any element in the placesdata.Places[city] array that has the title property set will be "truthy", so that object will be returned.
Just to expand on #ChristianScott's answer a bit, you could loop over placesdata["Places"] to get the city, and then use the find method to get the title.
So, for completeness:
var placesdata = {
"Places": {
"Berlin": [{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
let titles = []; // titles array
for (let city in placesdata["Places"]) { // for each city
titles.push(placesdata.Places[city].find(x => x.title).title); // find & push title
}
console.log(titles);
You can try this simple solution using for in:
var places = placesdata.Places;
for (var place in places) {
var component =
'<div class="title">' +
'<i class="dropdown icon"></i>' +
places[place][0].title +
'</div>' +
'<div class="content styleSetSubAccordion">' +
'<div class="ui two column divided grid ' + place + '\">' +
'</div>' +
'</div>'
if ($container.length) {
$container.append(component);
}
}

Convert JS array to objects

I have a problem with the correct converting array to the form what I need from a graph plugin. I have a JSON which looks like below, from this file I have to count how many titles I have (see pic. 1). Hope you will understand from the pictures.
[
{
"name": "Mike Frost",
"title": "value_1",
"gender": "Male"
},
{
"name": "Hans Karl",
"title": "value_6",
"gender": "Male"
},
{
"name": "Kelly Clarkson",
"title": "value_3",
"gender": "Female"
},
...
]
This what I've got so far:
This what I need:
There is my script which counts values from JSON.
var employeeData = require('json!../path/to/json.json');
var obj = [];
for (var i = 0, j = employeeData.length; i < j; i++) {
if (obj[employeeData[i]['title']]) {
obj[employeeData[i]['title']]++;
}
else {
obj[employeeData[i]['title']] = 1;
}
}
One convenient way to do this is with a map (either a real Map if you're using ES2015, or an object we're using as a map if you're using ES5 or earlier). You build a new array and also keep track of the array entries in the map keyed by the value_X value:
var json = '[' +
' {' +
' "name": "Mike Frost",' +
' "title": "value_1",' +
' "gender": "Male"' +
' },' +
' {' +
' "name": "Hans Karl",' +
' "title": "value_6",' +
' "gender": "Male"' +
' },' +
' {' +
' "name": "Another Six",' +
' "title": "value_6",' +
' "gender": "Male"' +
' },' +
' {' +
' "name": "Kelly Clarkson",' +
' "title": "value_3",' +
' "gender": "Female"' +
' },' +
' {' +
' "name": "Another 3",' +
' "title": "value_3",' +
' "gender": "Female"' +
' },' +
' {' +
' "name": "Yet Another 3",' +
' "title": "value_3",' +
' "gender": "Female"' +
' }' +
']';
// Parse the JSON
var data = JSON.parse(json);
// The new array we'll build
var newArray = [];
// Our "map"
var map = Object.create(null);
// Loop the parsed data
data.forEach(function(entry) {
// Get the existing new entry if any
var mapEntry = map[entry.title];
if (mapEntry) {
// We have one, increase its `value`
++mapEntry.value;
} else {
// There isn't one, create it with a count of 1
// and save it to the array
mapEntry = map[entry.title] = {
label: entry.title,
value: 1
};
newArray.push(mapEntry);
}
});
// Done
console.log(newArray);
That can be written much more concisely, but I wanted to call out the individual parts of what I was doing.
In ES2015+:
const json = `[
{
"name": "Mike Frost",
"title": "value_1",
"gender": "Male"
},
{
"name": "Hans Karl",
"title": "value_6",
"gender": "Male"
},
{
"name": "Another Six",
"title": "value_6",
"gender": "Male"
},
{
"name": "Kelly Clarkson",
"title": "value_3",
"gender": "Female"
},
{
"name": "Another 3",
"title": "value_3",
"gender": "Female"
},
{
"name": "Yet Another 3",
"title": "value_3",
"gender": "Female"
}
]`;
// Parse the JSON
const data = JSON.parse(json);
// The new array we'll build
const newArray = [];
// Our map
const map = new Map();
// Loop the parsed data
data.forEach(entry => {
// Get the existing new entry if any
let mapEntry = map.get(entry.title);
if (mapEntry) {
// We have one, increase its `value`
++mapEntry.value;
} else {
// There isn't one, create it with a count of 1
// and save it to the array
mapEntry = {
label: entry.title,
value: 1
};
map.set(entry.title, mapEntry);
newArray.push(mapEntry);
}
});
// Done
console.log(newArray);
You can use Array.prototype.reduce and a hash table to group the data - see demo below:
var object=[{name:"Mike Frost",title:"value_1",gender:"Male"},{name:"Hans Karl",title:"value_6",gender:"Male"},{name:"Kelly Clarkson",title:"value_3",gender:"Female"},{name:"Mike Frost",title:"value_1",gender:"Male"},{name:"Hans Karl",title:"value_6",gender:"Male"}];
var result = object.reduce(function(hash){
return function(prev, curr){
if(hash[curr.title])
hash[curr.title].value++;
else {
hash[curr.title] = {label: curr.title, value: 1};
prev.push(hash[curr.title]);
}
return prev;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
You could iterate the array and count the occurence of the same titles.
var data = [{ "name": "Mike Frost", "title": "value_1", "gender": "Male" }, { "name": "Hans Karl", "title": "value_6", "gender": "Male" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, ],
result = data.reduce(function (hash) {
return function (r, a) {
if (!hash[a.title]) {
hash[a.title] = { label: a.title, value: 0 };
r.push(hash[a.title]);
}
hash[a.title].value++;
return r;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 with Map
var data = [{ "name": "Mike Frost", "title": "value_1", "gender": "Male" }, { "name": "Hans Karl", "title": "value_6", "gender": "Male" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, ],
result = data.reduce(
(map =>
(r, a) =>
(!map.has(a.title) && map.set(a.title, r[r.push({ label: a.title, value: 0 }) - 1]), map.get(a.title).value++, r)
)(new Map), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

printing json using smart menu jquery

{"menu" :[{
"name": "Computers",
"children": [{
"name": "Notebook",
"children": [{
"name": "Apple"
}, {
"name": "Windows"
}]
}, {
"name": "Tablets",
"children": [{
"name": "Apple"
}, {
"name": "Android"
}, {
"name": "Windows"
}]
}]
}, {
"name": "Phones",
"children": [{
"name": "Android",
"children": [{
"name": "Samsung"
}, {
"name": "Nokia"
}, {
"name": "Lenovo"
}]
}, {
"name": "Windows Phones",
"children": [{
"name": "Microsoft"
}, {
"name": "Nokia"
}]
}]
}, {
"name": "Cameras",
"children": [{
"name": "Digital",
"children": [{
"name": "Nikon"
}, {
"name": "Fuji"
}]
}, {
"name": "DSLR",
"children": [{
"name": "Canon"
}, {
"name": "Nikon"
}]
}]
}]
}
and i want to print it so each parent have its children .. here is my code
$(document).ready(function() {
$.ajax({
url: 'menuData.json',
type: 'get',
dataType: 'json',
error: function(data){
alert("error");
},
success: function(data){
var i=0;
var j=0;
var n=0;
var obj=data;
var json = JSON.stringify(obj);
var s = JSON.parse(json);
for( i=0;i<s.menu.length;i++){
$("#main-menu").append(' <li>'+ s.menu[i].name +'</li>');
for( j=0;j<s.menu[i].children.length;j++)
{ $("#main-menu").append(' <li>'+ s.menu[i].children[j].name + '</li>');
for( n=0;n<s.menu[i].children[j].children.length;n++){
$("#main-menu").append(' <li>'+ s.menu[i].children[j].children[n].name +'</li>');
}
}
}
$('#main-menu').smartmenus({
subMenusSubOffsetX:1,
subMenusSubOffsetY: -8
});
}
});
});
but it ends up like this
any help please .. thanks in advance .. btw i am beginner so please help me .. thanks again
Your code is logically correct except you are always appending to the $("#main-menu"). Consider doing this:
...
for( var i=0; i < s.menu.length; i++)
{
$("#main-menu").append(' <li id="menu-list-' + i + '">' + s.menu[i].name + '</li>');
var list_length = s.menu[i].children.length;
if (list_length > 0)
$("#main-menu li#menu-list-" + i).append('<ul></ul>');
for( var j=0; j < list_length; j++)
{
$("#main-menu li#menu-list-" + i + " ul").append(' <li id="menu-list-' + i + '-children-list-' + j + '">'+ s.menu[i].children[j].name + '</li>');
var children_list_length = s.menu[i].children[j].children.length;
if(children_list_length > 0)
$("#main-menu li#menu-list-" + i + " ul li#menu-list-" + i + "-children-list-" + j).append("<ul></ul>");
for( var n=0; n < children_list_length; n++)
{
$("#main-menu li#menu-list-" + i + " ul li#menu-list-" + i + "-children-list-" + j + " ul").append(' <li>'+ s.menu[i].children[j].children[n].name +'</li>');
}
}
}
...

Categories