从JavaScript对象递归删除无效值 [英] Recursively remove nullish values from a JavaScript object

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

问题描述

我搜索了此内容,但找不到满意的答案,所以我在这里发布了自己的答案.

I searched for this but couldn't find a satisfactory answer so I'm posting my own answer here.

基本上,我想要一个功能:

Basically I wanted a function that:

  • 以对象作为参数
  • 递归地删除值为 null undefined [] {} 的属性''
  • 保留 0 false
  • 返回删除了这些属性的新对象
  • 最好是没有突变的功能样式

推荐答案

您可以在其中将三种类型的数据分开

You could separate the three types of data in

  • 数组,
  • 对象
  • 原始值

并通过减少复杂的数据类型并检查原始值来获取所需的子集.

and get the wanted subset by reducing the complex data types and checking the primitive values.

const
    isNullish = x => [
        v => v === '',
        v => v === null,
        v => v === undefined,
        v => v && typeof v === 'object' && !Object.keys(v).length
    ].some(f => f(x)),
    getArray = array => {
        var temp = array.reduce((r, v) => {
                v = getNotNullish(v);
                if (v !== undefined) r.push(v);
                return r;
            }, []);

        return temp.length ? temp : undefined;
    },
    getObject = object => {
        var hasValues = false,
            temp = Object.entries(object).reduce((r, [k, v]) => {
                v = getNotNullish(v);
                if (v !== undefined) {
                    r[k] = v;
                    hasValues = true;
                }
                return r;
            }, {});

        return hasValues ? temp : undefined;
    },
    getNotNullish = value => {
        if (Array.isArray(value)) return getArray(value);
        if (value && typeof value === 'object') return getObject(value);
        return isNullish(value) ? undefined : value;
    };


var data = {
        emptyArray: [],
        arrayWithNullish: [null, {}, [], undefined],
        null: null,
        undefined: undefined,
        emptyString: '',
        zero: 0,
        false: false,
        true: true,
        emptyObject: {},
        objectWithNullish: { null: null, emptyArray: [], undefined: undefined },
        nestedObject: {
            nestedObject: {
                null: null,
                one: 1,
                emptyObject: {}
            },
            nestedEmptyArray: [[], [[]]]
        }
    };

console.log(getNotNullish(data));

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于从JavaScript对象递归删除无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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