const product = {
name: 'widget',
price: 10,
avgRating: 4.5,
shippingWeight: '2 lbs',
shippingCost: 2,
shippingMethod: 'UPS'
}
const getProps = R.pick(['name', 'price'])
const result = getProps(product) // {name: 'widget', price: 10}
我想在getProps
中动态发送密钥(名称和价格)。
类似
const getProps = args => R.pick([..args]);
const result = getProps(['name', 'price'], product);
不起作用。
我应该怎么做?
答案 0 :(得分:2)
在选择中,您没有正确传递对象(as per the R.pick documentation)。
您可以这样做:
const product = {
name: 'widget',
price: 10,
avgRating: 4.5,
shippingWeight: '2 lbs',
shippingCost: 2,
shippingMethod: 'UPS'
}
const getProps = (obj, propsArr) => R.pick(obj, propsArr)
console.log(getProps(['name','price'], product))
console.log(getProps(['avgRating','shippingMethod'], product))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
或者您可以像这样对传递的参数进行解构:
const product = {
name: 'widget',
price: 10,
avgRating: 4.5,
shippingWeight: '2 lbs',
shippingCost: 2,
shippingMethod: 'UPS'
}
const getProps = (...args) => R.pick(...args)
console.log(getProps(['name','price'], product))
console.log(getProps(['shippingCost','shippingMethod'], product))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
答案 1 :(得分:0)
Ramda方法是咖喱的,这意味着每当参数数量小于Arity(函数期望的参数数量)时,都会返回一个新函数。因此,如果函数除fn(a,b,c)外,则在进行咖喱处理时,您可以执行fna = fn(a)
,fnab = fna(b)
等...
与经典currying不同,在ramda中,您还可以传递多个参数-fnab = fn(a, b)
。
您想要的已经是R.pick
工作的标准方式。可以使用单个参数调用它,然后返回一个期望另一个函数的函数,也可以一次使用所有参数调用它,并获得结果。
const product = {
name: 'widget',
price: 10,
avgRating: 4.5,
shippingWeight: '2 lbs',
shippingCost: 2,
shippingMethod: 'UPS'
}
const getProps = R.pick
console.log(getProps(['name','price'], product))
console.log(getProps(['shippingCost','shippingMethod'], product))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>