【问题标题】:How to join 2 array object using lodash如何使用 lodash 加入 2 个数组对象
【发布时间】: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 地图更好的方法吗?

【问题讨论】:

标签: javascript lodash


【解决方案1】:

b 减少到id 的映射到测试数组,然后映射a,并从映射中获取相关数组来创建每个对象:

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 bMap = b.reduce((acc, { name, aId }) => {
  const nameObject = { name }
  
  aId.forEach(id => {
    if(!acc.has(id)) acc.set(id, [])
    
    acc.get(id).push(nameObject)
  })

  return acc
}, new Map())

const result = a.map(o => ({ ...o, scores: bMap.get(o.id) }))

console.log(result)

【讨论】:

    猜你喜欢
    • 2013-09-02
    • 2020-09-16
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多