我有一个JavaScript对象数组,其中每个对象都可以有子对象,并且子对象的类型与父对象的类型相同,子对象可以有多个子对象。我想遍历所有节点并更改一些值。
[
    {
        "text": "Auto",
        "icon": "/libs/jstree/folder.png",
        "state": {
            "opened": true,
            "selected": true
        }
    },
    {
        "text": "BookMark1",
        "icon": "/libs/jstree/folder.png",
        "state": {
            "opened": true
        },
        "children": [
            {
                "text": "BookMark2",
                "icon": "/libs/jstree/folder.png",
                "state": {
                    "opened": true
                }
            },
            {
                "text": "BookMark3",
                "icon": "/libs/jstree/folder.png",
                "state": {
                    "opened": true
                }
            },
            {
                "text": "BookMark4",
                "icon": "/libs/jstree/folder.png",
                "state": {
                    "opened": true
                }
            },
            {
                "text": "BookMark5",
                "icon": "/libs/jstree/folder.png",
                "state": {
                    "opened": true
                }
            },
            {
                "text": "BookMark6",
                "icon": "/libs/jstree/folder.png",
                "state": {
                    "opened": true
                },
                "children": [
                    {
                        "text": "BookMark2",
                        "icon": "/libs/jstree/folder.png",
                        "state": {
                            "opened": true
                        }
                    },
                    {
                        "text": "BookMark3",
                        "icon": "/libs/jstree/folder.png",
                        "state": {
                            "opened": true
                        }
                    }
                ]
            },
            {
                "text": "BookMark7",
                "icon": "/libs/jstree/folder.png",
                "state": {
                    "opened": true
                }
            }
        ]
    }
]在上面的对象中,我希望遍历所有节点并删除"state“属性。我如何才能做到这一点。
发布于 2015-08-03 01:08:14
您需要在对象上使用递归函数进行迭代。我在这里为您创建了一个示例,也是遍历嵌套对象的最常用的方法:
function walk(item){
    for(index in item){
        console.log(item[index]);
        if(typeof item[index] == "object"){ 
            walk(item[index]); 
        }
    }
}使用这个函数作为基础,你可以扩展它的功能,做任何你真正需要的事情。如果你使用的是JQuery,他们会提供函数.each(function(index, item){})来做同样的事情。
如果我可以在其他方面提供帮助,请在此处更新您的帖子或评论。
https://stackoverflow.com/questions/31774167
复制相似问题