包含路径列表的 Ramda 函数和 returns 解构对象的函数
Ramda function that takes in list of paths and returns a function that destructures an object
你好,谁能指出我遇到的这个问题的正确方向,
基本上我有一个接收对象并解构它们的函数。
({ data: { accounts, loading } }) => ({
accounts,
loading,
})
我想制作一个 ramda 函数,它接受路径列表,从对象中深度提取值,然后 returns 从中提取一个对象。
实现上面相同的功能,我想使用这样的功能:
deepExtract(['data.accounts', 'data.loading'])
// input: { data: { accounts: 1, loading: 1 } }
// output: { accounts: 1, loading: 1 } (notice the keys doesn't have `data` in it.)
当前进度:
R.pipe(
R.map(R.split('.')), // <-- gives me a list that I can feed into lensPath [['data', 'accounts'], ['data', 'loading']
/* Can't figure out next steps but I'd like to run each of the list to:
* 1. lensProp
* 2. merge
*/
)(['data.accounts', 'data.loading'])
这是一个相当简单的版本,没有您额外的 split-on-:
要求:
const deepExtract = curry((paths, obj) => {
const fullPaths = map(split('.'), paths)
const names = map(last, fullPaths)
const vals = map(flip(path)(obj), fullPaths)
return zipObj(names, vals)
})
虽然我们可以使它免分,但它的可读性很强,而且可能不会是免分版本。
更新
添加 :
规则会使代码变得不那么令人愉快:
const deepExtract = curry((paths, obj) => {
const namedPaths = map(split(':'), paths)
const fullPaths = map(pipe(head, split('.')), namedPaths)
const names = map(ifElse(nth(1), nth(1), pipe(head, split('.'), last)), namedPaths)
const vals = map(flip(path)(obj), fullPaths)
return zipObj(names, vals)
})
我还没有认真想过如何避免与split('.')
重复。它可能可以毫不费力地完成。但这不太可能对性能造成严重影响,只是代码漂亮的问题。
你好,谁能指出我遇到的这个问题的正确方向,
基本上我有一个接收对象并解构它们的函数。
({ data: { accounts, loading } }) => ({
accounts,
loading,
})
我想制作一个 ramda 函数,它接受路径列表,从对象中深度提取值,然后 returns 从中提取一个对象。
实现上面相同的功能,我想使用这样的功能:
deepExtract(['data.accounts', 'data.loading'])
// input: { data: { accounts: 1, loading: 1 } }
// output: { accounts: 1, loading: 1 } (notice the keys doesn't have `data` in it.)
当前进度:
R.pipe(
R.map(R.split('.')), // <-- gives me a list that I can feed into lensPath [['data', 'accounts'], ['data', 'loading']
/* Can't figure out next steps but I'd like to run each of the list to:
* 1. lensProp
* 2. merge
*/
)(['data.accounts', 'data.loading'])
这是一个相当简单的版本,没有您额外的 split-on-:
要求:
const deepExtract = curry((paths, obj) => {
const fullPaths = map(split('.'), paths)
const names = map(last, fullPaths)
const vals = map(flip(path)(obj), fullPaths)
return zipObj(names, vals)
})
虽然我们可以使它免分,但它的可读性很强,而且可能不会是免分版本。
更新
添加 :
规则会使代码变得不那么令人愉快:
const deepExtract = curry((paths, obj) => {
const namedPaths = map(split(':'), paths)
const fullPaths = map(pipe(head, split('.')), namedPaths)
const names = map(ifElse(nth(1), nth(1), pipe(head, split('.'), last)), namedPaths)
const vals = map(flip(path)(obj), fullPaths)
return zipObj(names, vals)
})
我还没有认真想过如何避免与split('.')
重复。它可能可以毫不费力地完成。但这不太可能对性能造成严重影响,只是代码漂亮的问题。