const obj = {
psets: [...],
type: {
psets: [...]
}
}
想要容纳psets
道具。它们可能都不存在。
R.concat(R.pathOr([], ['type','pSets']), R.propOr([], 'pSets'));
**
Uncaught TypeError: function n(r){return 0===arguments.length||w(r)?n:t.apply(this,arguments)} does not have a method named "concat"
我在做什么错了?
答案 0 :(得分:1)
R.concat需要数组或字符串,而不是函数。您可以使用R.converge为concat准备阵列。
注意:R .__用作传入参数的占位符,您可以将这些参数分配给与最后一个参数不同的位置。
const obj = {
pSets: [1, 2],
type: {
pSets: [3, 4]
}
}
const fn = R.converge(R.concat, [
R.pathOr([], ['type','pSets']),
R.propOr([], 'pSets')]
)
const result = fn(obj)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
使代码成为DRYer的另一个选项是使用R.chain迭代路径,从对象中获取值,然后合并它们:
const obj = {
pSets: [1, 2],
type: {
pSets: [3, 4]
}
}
const fn = R.curry((paths, obj) => R.chain(R.pathOr([], R.__, obj), paths))
const result = fn([['pSets'], ['type','pSets']], obj)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>