如何在Ramda.js中连接两个数组?
我有下一个数据:
const inputData = {
content: [
{
info: ['Test-1-1', 'test-1-2'],
moreInfo: ['foo', 'bar'],
firstName: 'first',
lastName: 'lst',
notes: 'Some info goes here'
},
{
info: ['Test-2-1', 'test-2-2'],
moreInfo: ['foo-2', 'bar-2'],
firstName: 'first',
lastName: 'lst',
notes: 'Some info goes here-2'
},
]
}我可以很好地操作这些数据,但我不能将两个数组组合成一个。
我要做的是
info: ['Test-2-1', 'test-2-2'],
moreInfo: ['foo-2', 'bar-2'],端回
"theInfo": ["Test-1-1", "test-1-2", "foo", "bar"]我的代码:
const allInfo = (R.props(['info', 'moreInfo']));
const returnNewObject = R.applySpec({
// More code here to do other stuff
theInfo: allInfo,
})
R.map(returnNewObject, inputData.content)我得到的是:
{
// other info
"theInfo": [["Test-1-1", "test-1-2"], ["foo", "bar"]]
}我试过的是:
文档中的示例
R.concat(4,5,6,1,2,3);
但是它返回空对象数组,因为某些原因它不像文档中那样工作
发布于 2021-06-03 06:39:48
答案是:
const allInfo = R.compose(R.flatten, (R.props(['info', 'moreInfo'])))End返回扁平数组:
["Test-1-1", "test-1-2", "foo", "bar"]发布于 2021-06-03 12:33:04
您当然可以编写类似的东西(为演示目的附加一个字段组合)
const extract = applySpec ({
theInfo: compose (unnest, props (['info', 'moreInfo'])),
fullName: compose (join (' '), props (['firstName', 'lastName'])),
notes: prop ('notes')
})
const process = evolve ({
content: map (extract)
})
const inputData = {content: [{info: ['Test-1-1', 'test-1-2'], moreInfo: ['foo', 'bar'], firstName: 'first', lastName: 'lst', notes: 'Some info goes here'}, {info: ['Test-2-1', 'test-2-2'], moreInfo: ['foo-2', 'bar-2'], firstName: 'first', lastName: 'lst', notes: 'Some info goes here-2'}]}
console .log (process (inputData)).as-console-wrapper {max-height: 100% !important; top: 0}<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script> const {applySpec, compose, unnest, props, join, prop, evolve, map} = R </script>
如果没有其他用途,我们可以将extract嵌入到process中,如下所示:
const process = evolve ({
content: map (applySpec ({
theInfo: compose (unnest, props (['info', 'moreInfo'])),
fullName: compose (join (' '), props (['firstName', 'lastName'])),
notes: prop('notes')
}))
})但是,一个很好的问题是,Ramda在使用普通JS版本的基础上增加了多少:
const process = ({content, ...rest}) => ({
...rest,
content: content.map (({info, moreInfo, firstName, lastName, notes}) => ({
theInfo: info .concat (moreInfo),
fullName: `${firstName} ${lastName}`,
notes
}))
})如果我已经在我的项目中使用了Ramda,我会选择稍微更具声明性的Ramda版本;不过,这是一个很接近的选择。我当然不会仅仅为了这个而加上兰达。
发布于 2021-06-03 06:22:29
您可以使用.flat来扁平数组。
theInfo.flat() //["Test-1-1", "test-1-2", "foo", "bar"]https://stackoverflow.com/questions/67816280
复制相似问题