问题描述
我正在尝试在两个不同的数据源上使用 map 和 forEach 创建一组有效负载。有效载荷数组应如下所示:
const payloads = [{
accountId: 1,tagId: 'tag1',notes: 'random note'
},{
accountId: 1,tagId: 'tag2',tagId: 'tag3',{
accountId: 2,...]
我有以下变量:
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 的 forEach
总是按原样返回输入数组。因此,对于每个 map
操作,您在概念上返回的是 tags
数组而无需任何转换。您需要的是亨利回答的另一个地图运算符。但是嵌套的 map
仍然会导致嵌套数组。因此,结果不是您所需的结果,而是
[
[ {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>
尝试同时使用 map
而不是 forEach
:
const ids = [1,'tag3']
const note = 'random note'
const results = _.flatten(_.map(ids,tag => ({
accountId: id,notes: note
}))));
console.log(results)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
纯 JavaScript:
const ids = [1,'tag3']
const note = 'random note'
const results = ids.map(id => tags.map(tag => ({
accountId: id,notes: note
}))).flat();
console.log(results)