【发布时间】: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
}
)}));
这只是返回一个标签数组。我不确定我哪里出错了,但我认为我没有正确理解链接。我在这里做错了什么?
【问题讨论】:
-
你不需要整个 lodash 库,只需要 map 和 foreach 函数。你可以使用内置的 Array.prototype.forEach 和 Array.prototype.map 来代替。
标签: javascript node.js reactjs lodash underscore.js