gpt4 book ai didi

javascript - Ramda,在函数中发送参数

转载 作者:行者123 更新时间:2023-12-01 00:59:54 27 4
gpt4 key购买 nike

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 中,我想动态发送 key (名称和价格)。

类似

const getProps = args => R.pick([..args]);
const result = getProps(['name', 'price'], product);

不起作用。

我应该怎么做?

https://plnkr.co/edit/MHv5AMEO3p9dxiNCvQ80?p=preview

最佳答案

在您的选择中,您没有正确传递对象( 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>

关于javascript - Ramda,在函数中发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56180942/

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