【问题标题】:How to chain Map and forEach in lodash?如何在 lodash 中链接 Map 和 forEach?
【发布时间】:2021-05-03 19:28:20
【问题描述】:

我正在尝试在两个不同的数据源上使用 map 和 forEach 创建一组有效负载。有效载荷数组应如下所示:

const payloads = [{
  accountId: 1,
  tagId: 'tag1',
  notes: 'random note'
}, 
{
  accountId: 1,
  tagId: 'tag2',
  notes: 'random note'
}, 
{
  accountId: 1,
  tagId: 'tag3',
  notes: 'random note'
},
{
  accountId: 2,
  tagId: 'tag1',
  notes: 'random note'
},
...]

我有以下变量:

const ids = [1, 2, 3]
const tags = ['tag1', 'tag2', 'tag3']
const notes = 'random note'

我想使用此数据创建一个有效负载数组,以便每个 id 都有一个单独的有效负载和每个注释。

我尝试使用 lodash map 和 forEach 执行以下操作:

import { forEach, map } from 'lodash';

  const payloads = map(ids, id => forEach(tags, tag => {
    return ({
    accountId: id,
    tagId: tag,
    notes: note
  }
  )}));

这只是返回一个标签数组。我不确定我哪里出错了,但我认为我没有正确理解链接。我在这里做错了什么?

【问题讨论】:

标签: javascript node.js reactjs lodash underscore.js


【解决方案1】:

首先,lodash 的forEach 总是按原样返回输入数组。因此,对于每个map 操作,您在概念上都返回tags 数组而不进行任何转换。您需要的是亨利回答的另一个地图操作员。但是嵌套的map 仍然会导致嵌套数组。因此,结果不是您需要的结果,而是

[
    [ {Object}, {Object}, {Object} ],
    [ {Object}, {Object}, {Object} ],
    [ {Object}, {Object}, {Object} ]
]

要处理嵌套,您需要在转换后的结果上使用Array.prototype.flat

所以你的代码看起来像

const ids = [1, 2, 3]
const tags = ['tag1', 'tag2', 'tag3']
const notes = 'random note'
const payloads = _.map(ids, id => _.map(tags, tag => {
        return ({
        accountId: id,
        tagId: tag,
        notes: notes
      })})).flat();
console.log(payloads);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

【讨论】:

  • 感谢您的澄清。我试过这样做,但由于某种原因,accountId 键是所有 id 的数组
  • @Jav 那么肯定还有别的东西。我添加了一种可运行形式的代码 sn-p。请尝试一下。它清楚地显示了您想要的输出。
  • 我的输入有误,非常感谢您的解释!
【解决方案2】:

尝试两次都使用map,而不是forEach

const ids = [1, 2, 3]
const tags = ['tag1', 'tag2', 'tag3']
const note = 'random note'

const results = _.flatten(_.map(ids, id => _.map(tags, tag => ({
  accountId: id,
  tagId: tag,
  notes: note
}))));

console.log(results)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

纯 JavaScript:

const ids = [1, 2, 3]
const tags = ['tag1', 'tag2', 'tag3']
const note = 'random note'

const results = ids.map(id => tags.map(tag => ({
    accountId: id,
    tagId: tag,
    notes: note
}))).flat();

console.log(results)

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多