[英]Ramda omit key and value if they both match
I have an object that contains some data. 我有一个包含一些数据的对象。 I'd like to pick out certain keys and then also omit a key and value if they both match.
我想挑选某些键,然后如果它们都匹配,则也省略键和值。 Here's my object:
这是我的对象:
const obj = {
title: 'some title',
description: 'some descrption',
image: 'default_image.png'
}
What I'd like to do, is to extract description
and image
, and then omit the image
if it has a value of 'default_image.png'
. 我想做的是提取
description
和image
,然后忽略image
如果它的值为'default_image.png'
。
const fn = R.compose(
// if image === 'default_image.png' then omit it
R.pickAll(['description', 'image'])
)
Not sure what the best ramda function is to use for the second part of the above. 不知道上面第二部分使用的最佳ramda函数是什么。
You could create two different functions and one boolean function that checks for the field applying it with ramda's ifElse
您可以创建两个不同的函数和一个布尔函数,以使用ramda的
ifElse
检查对其应用的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));
The simplest way I could think of is using pickBy
我能想到的最简单的方法是使用
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))
I would probably do something like 我可能会做类似的事情
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. dissoc
返回删除了特定键的对象的副本。 propEq
tests if the given property of an object matches the value supplied. propEq
测试对象的给定属性是否与提供的值匹配。 And when
takes a predicate and a conversion function. 而
when
带有谓词和转换函数。 If the predicate matches the supplied data, the result of calling the conversion function on that data is returned, otherwise that data is returned unchanged. 如果谓词与提供的数据匹配,则返回对该数据调用转换函数的结果,否则返回该数据不变。
Note that I chose pick
instead of pickAll
. 请注意,我选择了
pick
而不是pickAll
。 The only difference is that pick
skips keys it doesn't find, pickAll
returns them with value undefined
. 唯一的区别是
pick
跳过了找不到的键, pickAll
返回了它们的值undefined
。
You can see this in the Ramda REPL . 您可以在Ramda REPL中看到这一点。
If you were always going to operate on a list instead of individual objects, you might switch from pick
to project
: 如果您总是要操作列表而不是单个对象,则可以从
pick
切换到project
:
const fn = pipe(
project(['description', 'image']),
map(when(propEq('image', 'default_image.png'), dissoc('image')))
);
fn(objects);
This one is also available on the Ramda REPL . Ramda REPL也提供此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.