递归搜索 JSON 并删除某些子对象

Recursively search JSON and delete certain sub objects

本文关键字:对象 删除 搜索 JSON 递归      更新时间:2023-09-26

我需要递归搜索一个复杂的 json 对象,并删除与任何以"_"开头的键关联的对象。

到目前为止,我有:

sanitize: function(json){
    for(var i in json){
        if(json[i]){
            if(i.substring(0,1) == "_")
                delete json[i];
            else
                this.sanitize(json[i]);
        }
    }
    console.log(json);
    return json;
}

我超过了最大调用堆栈。

尝试使用自己的数组,并确保子对象不是循环引用,并确保它们是对象。

function sanitize(json) {
    var stack = [];
    var done = [];
    do {
        for(var x in json) {
            if(x.charAt(0) === '_') {
                delete json[x];
            } else if(done.indexOf(json[x]) === -1 && typeof json[x] === 'object') {
                stack.push(json[x]);
                done.push(json[x]);
            }
        }
    } while(json = stack.pop());
}