我搜索过这个但找不到满意的答案所以我在这里发布我自己的答案。
基本上我想要一个函数:
- 接受一个对象作为参数
- 递归地删除值为
null
、undefined
、[]
、{}
或的属性''
- 保留
0
和false
值 - 返回一个删除了这些属性的新对象
- 最好是没有突变的函数式风格
最佳答案
这是我想出的。 (感谢 Nina 提供样本;)
const is_obj = x => x !== null && typeof x === 'object';
const is_arr = x => Array.isArray(x);
const nullish = x =>
( typeof x !== 'number'
&& typeof x !== 'boolean'
&& typeof x !== 'function'
)
&&
( x === undefined
|| x === null
|| x === ''
|| Object.values(x).reduce((res, x) =>
res && nullish(x), true)
);
const clean = x =>
[x]
.map(x => Object.entries(x))
.map(x => x.map(([k, v]) =>
is_arr(v) ? [ k
, v.map(vv => is_obj(vv) ? clean(vv) : vv)
]
: is_obj(v) ? [ k
, clean(v)
]
: [ k
, v
]))
.map(x => x.filter(([k, v]) => !nullish(v)))
.map(x => Object.fromEntries(x))
.pop();
console.log(clean(data));
<script>
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: [[], [[]]]
}
};
</script>
关于javascript - 递归地从 JavaScript 对象中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413342/