繁体   English   中英

Ramda concat 数组问题

[英]Ramda concat array issue

如何在 Ramda.js 中连接两个 arrays?

我有下一个数据:

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'

    },
  ]
}

我可以很好地处理这些数据,但我不能将两个 arrays 合二为一。

我需要做的就是采取

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]);

但它返回空 object 数组,由于某些原因,它不像文档中那样工作

答案是:

const allInfo = R.compose(R.flatten, (R.props(['info', 'moreInfo'])))

结束它返回展平数组:

["Test-1-1", "test-1-2", "foo", "bar"]

你当然可以写这样的东西(带有额外的字段组合用于演示目的)L

 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>

如果我们没有其他用途,我们可以像这样在process嵌入extract

const process = evolve ({
  content: map (applySpec ({
    theInfo: compose (unnest, props (['info', 'moreInfo'])),
    fullName: compose (join (' '), props (['firstName', 'lastName'])),
    notes: prop('notes')
  }))
})

但是有一个很好的问题是 Ramda 增加了多少使用 vanilla JS 版本:

const process = ({content, ...rest}) => ({
  ...rest,
  content: content.map (({info, moreInfo, firstName, lastName, notes}) => ({
    theInfo: info .concat (moreInfo),
    fullName: `${firstName} ${lastName}`,
    notes
  }))
})

如果我已经在我的项目中使用 Ramda,我会选择更具声明性的 Ramda 版本; 不过,这是一个接近的电话。 我当然不会为此添加 Ramda。

您可以使用.flat来展平阵列。

theInfo.flat() //["Test-1-1", "test-1-2", "foo", "bar"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM