0

我需要有关遍历以下 JSON 中每个元素的帮助,并获取键和值并将其打印为无序列表。

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"
                            })
                        })
                    })

                })
            });
4

1 回答 1

1

目前尚不清楚您想要什么形式的输出,但这里有一种遍历数据结构并生成一些缩进输出的方法。此外,数据定义中不需要括号(我已删除它们以使数据更易于阅读)。

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);

工作演示:http: //jsfiddle.net/jfriend00/6kAn3/

于 2014-01-25T15:05:58.593 回答