I have to create a menu tree from a JSON.
The JSON looks like this:
[
{
"For Home Products":[
"Menu Free Antivirus",
"Menu Premium",
"Menu Internet Security"
]
},
{
"For Business Products":[
{
"Client/Servers":[
"Menu Professional Security",
"Menu Server Security",
"Menu Business Security Suite",
"Menu Endpoint Security"
]
},
{
"Integration":[
"Anti-Malware",
"Antispam SDK (SPACE)",
"Rebranding & Bundling",
"Integration Services"
]
},
"Small Business",
"Managed Services",
{
"Gateways":[
"Menu MailGate",
"Menu MailGate Suite",
"Menu AntiVir Exchange",
"Menu WebGate",
"Menu WebGate Suite",
"Menu GateWay Bundle",
"Menu SharePoint"
]
}
]
}
]
The way I tried to solve the problem looks like this:
function setData(data) {
console.log(data);
$.each(data, function(key1, value1) {
$.each(value1, function(key2, value2) {
var x = document.createElement("ul");
x.setAttribute("id", key2);
document.body.appendChild(x);
$.each(value2, function(key3, value3) {
// console.log(value3);
var z = document.createElement("li");
z.setAttribute("id", value3);
document.getElementById(key2).appendChild(z);
console.log(value3);
})
})
})
return setData;
}
setData(data);
Now, my problem is that the classes are not added correctly. e.g:
<li id="[object Object]"></li>
I know that the error is because I'm trying to make a class from an object, but I'm trying to solve this problem for two hours now and I can't find the correct way of doing this without hard coding it.
Output
Code Snippet (Run)
var data = [
{
"For Home Products":[
"Menu Free Antivirus",
"Menu Premium",
"Menu Internet Security"
]
},
{
"For Business Products":[
{
"Client/Servers":[
"Menu Professional Security",
"Menu Server Security",
"Menu Business Security Suite",
"Menu Endpoint Security"
]
},
{
"Integration":[
"Anti-Malware",
"Antispam SDK (SPACE)",
"Rebranding & Bundling",
"Integration Services"
]
},
"Small Business",
"Managed Services",
{
"Gateways":[
"Menu MailGate",
"Menu MailGate Suite",
"Menu AntiVir Exchange",
"Menu WebGate",
"Menu WebGate Suite",
"Menu GateWay Bundle",
"Menu SharePoint"
]
}
]
}
]
function setData(data) {
//console.log(data);
$.each(data, function(key1, value1) {
$.each(value1, function(key2, value2) {
var x = document.createElement("ul");
x.setAttribute("id", key2);
document.body.appendChild(x);
$.each(value2, function(key3, value3) {
// console.log(value3);
var z = document.createElement("li");
z.setAttribute("id", value3);
z.innerHTML = value3;
document.getElementById(key2).appendChild(z);
console.log(value3);
})
})
})
return setData;
}
setData(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>