从对象(包括父对象)中递归删除 undefined [英] recursively remove undefined from object (including parent)

查看:50
本文介绍了从对象(包括父对象)中递归删除 undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一个问题的解决方案,如果那里没有值,我需要从嵌套对象(包括所有父对象)中删除 undefined,请考虑示例:

I'm trying to find a solution to a problem where I need to remove undefined from nested object including all parents if there are no values there, please consider example:

var test = {
  foo : {
    bar : {
      baz : undefined
    }
  },
  bar : 1
}

所以我的任务是将 baz 与 bar 和 foo 一起删除,但在根级别仍然有 bar;我知道用 2 个 for 循环来解决是一项微不足道的任务,我只是想知道是否有更优雅和干净的解决方案来代替使用递归堆栈?提前致谢!

So my task is to remove baz along with bar and foo but still have bar at the root level; I know that it's trivial task to solve with 2 for loops, I'm just wondering if there are more elegant and clean solutions which will use recursive stack instead? Thanks in advance!

推荐答案

深度优先递归应该可以处理:

Depth-first recursion should be able to handle it:

function cleanse(obj, path) {
    Object.keys(obj).forEach(function(key) {
        // Get this value and its type
        var value = obj[key];
        var type = typeof value;
        if (type === "object") {
            // Recurse...
            cleanse(value);
            // ...and remove if now "empty" (NOTE: insert your definition of "empty" here)
            if (!Object.keys(value).length) {
                delete obj[key]
            }
        }
        else if (type === "undefined") {
            // Undefined, remove it
            delete obj[key];
        }
    });
}

示例:

var test = {
  foo : {
    bar : {
      baz : undefined
    }
  },
  bar : 1
};
cleanse(test);
function cleanse(obj, path) {
    Object.keys(obj).forEach(function(key) {
        // Get this value and its type
        var value = obj[key];
        var type = typeof value;
        if (type === "object") {
            // Recurse...
            cleanse(value);
            // ...and remove if now "empty" (NOTE: insert your definition of "empty" here)
            if (!Object.keys(value).length) {
                delete obj[key]
            }
        }
        else if (type === "undefined") {
            // Undefined, remove it
            delete obj[key];
        }
    });
}
console.log(test);

请注意,仅访问名称不是 Symbols (ES2015+) 的对象的 ownenumerable 属性.如果您还想处理从原型继承的属性、不可枚举的属性或名称为 Symbols 的属性,则需要进行调整以处理它.(您可以通过 getOwnPropertyNames 在 ES5 或更高版本的 JavaScript 引擎上获取不可枚举的属性.)

Note that that only visits own, enumerable properties of the objects whose names are not Symbols (ES2015+). If you also want to handle properties inherited from prototypes, or non-enumerable properties, or properties whose names are Symbols, you'll need to adjust to handle that. (You can get non-enumerable properties on an ES5 or later JavaScript engine via getOwnPropertyNames.)

这篇关于从对象(包括父对象)中递归删除 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆