javascript Ramda:删除具有动态键的空对象

camsedfj  于 2022-12-28  发布在  Java
关注(0)|答案(3)|浏览(124)

我有这个对象,其中addon_sizes键是动态的,即"1","2", "3", "4"

const sizes = {
 "addon_sizes": {
        "1": ["a", "b"],
        "2": ["c"],
        "3": null,
        "4": []
    }
}

我需要删除此对象中值为null/undefined/empty数组的所有键/值对。
因此,应从列表中删除键“3”和“4”。
到目前为止我所尝试的是:

const newObj = R.reject(R.anyPass([R.isEmpty, R.isNil]))(sizes.addon_sizes);

但这并没有删除null或空值。

fv2wmkja

fv2wmkja1#

通过拾取所有不为空或nil的属性来创建新对象:

const { pickBy, complement, anyPass, isEmpty, isNil } = R

const fn = pickBy(complement(anyPass([isEmpty, isNil])))

const sizes = {"addon_sizes":{"1":["a","b"],"2":["c"],"3":null,"4":[]}}

const result = fn(sizes.addon_sizes)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
2uluyalo

2uluyalo2#

既然你已经标记了javascript:
您可以遍历对象条目,并使用delete关键字删除负属性或负长度属性。

const sizes = {
    "addon_sizes": {
        "1": ["a", "b"],
        "2": ["c"],
        "3": null,
        "4": []
    }
};

Object.entries(sizes.addon_sizes).forEach(([ key, value ]) => {
  if(!value || !value.length)
    delete sizes.addon_sizes[key];
});

console.log(sizes);
yhqotfr8

yhqotfr83#

这取决于你对remove的定义。如果你想改变你的原始对象,那么Ramda不会提供任何帮助。如果你想创建一个没有这些属性的副本,你的代码看起来已经工作了,尽管它仍然需要应用到你的输入对象。这里我们使用overlensProp来实现

const cleanAddons = over (
  lensProp ('addon_sizes'), 
  reject (anyPass ([isNil, isEmpty]))
)

const sizes = { addon_sizes: {1: ["a", "b"], 2: ["c"], 3: null, 4: []}}

console .log (cleanAddons (sizes))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {over, lensProp, reject, anyPass, isNil, isEmpty} = R     </script>

lensProp ('addon_sizes')创建了一个lens,它专注于addon_sizes属性,over使用这个镜头和基于reject的函数来创建一个函数,该函数将创建原始对象的副本,并从addon_sizes中删除空值或nil值。
当只使用两个函数时,我发现either (f, g)anyPass ([f, g])更具语义性,所以我更喜欢这个版本,但它做的是同样的事情:

const cleanAddons = over (
  lensProp ('addon_sizes'), 
  reject (either (isNil, isEmpty))
)

相关问题