gpt4 book ai didi

javascript - Ramda 删除嵌套的空值

转载 作者:行者123 更新时间:2023-12-05 00:36:28 27 4
gpt4 key购买 nike

我想从对象中删除所有空值。让我们假设:

const data = {
key1: 'ok',
key2: null,
key3: '', // should be removed too
key4: {
inner_key1: 'aaa',
inner_key2: null
}
}
我做的是这个
const clean = R.reject(R.either(R.isNil, R.isEmpty))
而这项工作:
{"key1":"ok","key4":{"inner_key1":"aaa","inner_key2":null}}
除了 如您所见,对于嵌套对象,inner_key2 存在,应该被过滤掉。
使用 ramda,我怎样才能删除这个嵌套值呢?

最佳答案

创建一个递归函数,在清理对象后对属性进行迭代,并在每个属性上调用 clean,这是一个对象:

const { pipe, reject, either, isNil, isEmpty, map, when, is } = R

const clean = o => pipe(
reject(either(isNil, isEmpty)),
map(when(is(Object), clean))
)(o)

const data = {"key1":"ok","key2":null,"key3":"","key4":{"inner_key1":"aaa","inner_key2":null}}
const result = clean(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous"></script>

关于javascript - Ramda 删除嵌套的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67504928/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com