Javascript object traversal [duplicate]

*爱你&永不变心* 提交于 2019-12-14 03:15:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!