从一系列可能的path中获取string

我有一个场景,我需要抓住一个对象的string的第一个匹配项,但只有匹配发生在一个已经预先定义的path中。

{ id: 'I60ODI', description: 'some random description' } { foo: 'bar', description: { color: 'green', text: 'some description within text' } } 

当提供上述两个对象中的任何一个时,我希望解决scheme返回some random descriptionsome description within text ,只要两个可能的path是obj.descriptionobj.description.text 。 未来可能还需要添加新的path,所以添加它们需要很容易。

这是迄今为止我已经实施的解决scheme,但对我来说,这似乎并不是最佳的。

 // require the ramda library const R = require('ramda'); // is the provided value a string? const isString = R.ifElse(R.compose(R.equals('string'), (val) => typeof val), R.identity, R.always(false)); const addStringCheck = t => R.compose(isString, t); // the possible paths to take (subject to scale) const possiblePaths = [ R.path(['description']), R.path(['description', 'text']) ]; // add the string check to each of the potential paths const mappedPaths = R.map((x) => addStringCheck(x), possiblePaths); // select the first occurrence of a string const extractString = R.either(...mappedPaths); // two test objects const firstObject = { description: 'some random description' }; const secondObject = { description: { text: 'some description within text' } }; const thirdObject = { foo: 'bar' }; console.log(extractString(firstObject)); // 'some random description' console.log(extractString(secondObject)); // 'some description within text' console.log(extractString(thirdObject)); // false 

如果一个经验丰富的函数程序员可能会为我提供一些替代方法来实现,我将不胜感激。 谢谢。

这将工作,我认为它更清洁:

 const extract = curry((defaultVal, paths, obj) => pipe( find(pipe(path(__, obj), is(String))), ifElse(is(Array), path(__, obj), always(defaultVal)) )(paths)) const paths = [['description'], ['description', 'text']] extract(false, paths, firstObject) //=> "some random description" extract(false, paths, secondObject) //=> "some description within text" extract(false, paths, thirdObject) //=> false 

我个人会发现在一个更好的默认值比false ,但这是你的电话。

这避免了映射到所有path,当find第一个path时停止。 它也使用拉姆达的is用你的复杂的isString R.is(String) 。 而咖喱让你提供第一个或前两个参数来创build一个更有用的function。

你可以在Ramda REPL中看到这个动作。