问题
I need Help regarding the traversal of each and every elements in the following JSON and get both key and value and print it like an unordered list.
var dataSource = ({
"Items": ({
"Deserts": ({}),
"Veg": ({
"VegPulao": "Veg Pulao",
"PalakPaneer": "Palak Paneer",
"PaneerButterMasala": "Paneer Butter Masala"
}),
"Chicken": ({
"Tandoori": "Tandoori special"
}),
"Hot drinks": ({
"Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
"Tea": ({"Red": "Red Tea", "Black": "Black Tea"}),
"BadamMilk": "Hot Badam Milk",
"Bornvita": "Hot Bornvita",
"Milk": "Hot Milk"
}),
"Juice": ({
"Mango": "Mango",
"Berry": "Berry",
"Grapes": "Grapes",
"Wine": ({
"Rose": "Rose",
"Red wine": "Red",
"Apple": "Apple",
"Hard drinks": ({
"Royal challenge": "Royal challenge",
"Blender's Pride": "Blender's Pride"
})
})
})
})
});
回答1:
It is not clear exactly what form of output you want, but here's a method of traversing your data structure and generating some indented output. Also, parentheses are not necessary in your data definition (I have removed them to make the data easier to read).
function output(str, level) {
var obj = document.getElementById("output");
var div = document.createElement("div");
var node = document.createTextNode(str);
div.style.marginLeft = (level * 20) + "px";
div.appendChild(node);
obj.appendChild(div);
}
function traverseObject(obj, level) {
for (var prop in obj) {
if (typeof obj[prop] === "object") {
output(prop, level);
traverseObject(obj[prop], level + 1);
} else {
output(prop + ": " + obj[prop], level);
}
}
}
traverseObject(dataSource, 0);
Working demo: http://jsfiddle.net/jfriend00/6kAn3/
来源:https://stackoverflow.com/questions/21326574/javascript-object-traversal