【发布时间】:2022-01-21 12:04:29
【问题描述】:
我想用 lodash 将 a 和 b 连接起来,这是我的数据
const a =
[ { id: 1, job: 'engineer' }
, { id: 2, job: 'police' }
, { id: 3, job: 'thief' }
]
const b =
[ { name: 'test1', score: 1, aId: [ 1, 2 ] }
, { name: 'test2', score: 3, aId: [ 1, 3 ] }
]
这是我想要的输出
const result =
[ { id: 1, job: 'engineer', score: [ {name: 'test1'}, {name: 'test2'} ] }
, { id: 2, job: 'police', score: [] }
, { id: 3, job: 'thief', score: [ {name: 'test 3'} ] }
]
这是我尝试的,我正在使用 2 个地图数据,在第二个地图中我使用了 2 个数组之间的包含检查..
_.map(a, function(data:any) {
const name = _.map(b, function(dataB:any) {
// in here I check
const isValid = dataB.aId.includes(a.id)
if(isValid){
return {
name = dataB.name
}
}
})
return {
id: data.id
job: data.job
score: name
}
});
这种方法也有效,但他们有比使用 2 地图更好的方法吗?
【问题讨论】:
-
感谢您迄今为止的努力。
-
为什么
name:'test 3'不知从何而来?
标签: javascript lodash