如果键和值都匹配,Ramda 会忽略它们

Ramda omit key and value if they both match

我有一个包含一些数据的对象。我想挑选出某些键,然后如果它们都匹配则省略一个键和值。这是我的对象:

const obj = {
  title: 'some title',
  description: 'some descrption',
  image: 'default_image.png'
}

我想做的是提取 descriptionimage,然后如果 image 的值为 'default_image.png',则省略 image

const fn = R.compose(
  // if image === 'default_image.png' then omit it
  R.pickAll(['description', 'image'])
)

不确定上述第二部分的最佳 ramda 函数是什么。

您可以创建两个不同的函数和一个布尔函数来检查应用它的字段与 ramda 的 ifElse

const obj1 = {
  title: 'some title',
  description: 'some descrption',
  image: 'default_image.png'
}

const obj2 = {
  title: 'title',
  description: 'descrption',
  image: 'image.png'
}

const withImage = R.pickAll(['description', 'image']);
const withoutImage = R.pickAll(['description']);
const hasDefault = obj => obj['image'] == 'default_image.png'

const omit = R.ifElse(hasDefault, withoutImage, withImage);

console.log(omit(obj1));
console.log(omit(obj2));

我能想到的最简单的方法是使用 pickBy

const hasDefault = (val, key) => key == 'image' && val == 'default_image.png' ? false : true
console.log(R.pickBy(hasDefault, obj1))
console.log(R.pickBy(hasDefault, obj2))

我可能会做类似的事情

const fn = pipe(
  when(propEq('image', 'default_image.png'), dissoc('image')),
  pick(['description', 'image'])
);

dissoc returns a copy of an object with a specific key removed. propEq tests if the given property of an object matches the value supplied. And when 采用谓词和转换函数。如果谓词与提供的数据匹配,则返回对该数据调用转换函数的结果,否则返回该数据不变。

注意我选择了pick instead of pickAll。唯一的区别是 pick 跳过它找不到的键,pickAll returns 它们的值为 undefined.

你可以在 Ramda REPL.

中看到这个

如果您总是要对列表而不是单个对象进行操作,您可以从 pick 切换到 project:

const fn = pipe(
  project(['description', 'image']),
  map(when(propEq('image', 'default_image.png'), dissoc('image')))
);

fn(objects);

这个也可以在 Ramda REPL.

上找到