将异步等待中基于id的两个json数组合并到javascript中

问题描述 投票:0回答:1

我有以下这些 json 数组。

const arrA = [
  {
    id: '12',
    generalId: 'B143',
    total: 10,
  },
  {
    id: '12',
    generalId: 'B145',
    total: 20,
  },
  {
    id: '13',
    generalId: 'B145',
    total: 30,
  },
  {
    id: '13',
    generalId: 'B143',
    total: 40,
  }
]
const arrB = [
  {
    generalId: 'B145',
    id: '13',
    name: 'EMP A',
    count: 1,
  },
  {
    generalId: 'B145',
    id: '12',
    name: 'EMP B',
    count: 2,
  },
  {
    generalId: 'B143',
    id: '13',
    name: 'EMP A',
    count: 3,
  },
  {
    generalId: 'B143',
    id: '12',
    name: 'EMP B',
    count: 4,
  }
]

通过匹配我在下面尝试过的解决方案的 ID 来合并上面的 json 数组。

Solution 1
const mergedResult = arrA.map((item, i) => {
  if ((item.generalId === arrB[i].generalId)) {
    return Object.assign({}, item, arrB[i]);
  }
})

const sample = Promise.all(arrA.map((item, i) => {
  if ((item.generalId === arrB[i].generalId)) {
    return Object.assign({}, item, arrB[i]);
  }
})
)

但是它抛出了

generalId
未定义的错误。

我想要的结果是这样的:

const Result = [
  {
    generalId: 'B145',
    id: '13',
    name: 'EMP A',
    count: 1,
    total: 30,
  },
  {
    generalId: 'B145',
    id: '12',
    name: 'EMP B',
    count: 2,
    total: 20,
  },
  ... 
]
javascript arrays asynchronous async-await
1个回答
0
投票

您可以按照以下方式进行:

const arrA = [
  {
    id: '12',
    generalId: 'B143',
    total: 10,
  },
  {
    id: '12',
    generalId: 'B145',
    total: 20,
  },
  {
    id: '13',
    generalId: 'B145',
    total: 30,
  },
  {
    id: '13',
    generalId: 'B143',
    total: 40,
  }
]
const arrB = [
  {
    generalId: 'B145',
    id: '13',
    name: 'EMP A',
    count: 1,
  },
  {
    generalId: 'B145',
    id: '12',
    name: 'EMP B',
    count: 2,
  },
  {
    generalId: 'B143',
    id: '13',
    name: 'EMP A',
    count: 3,
  },
  {
    generalId: 'B143',
    id: '12',
    name: 'EMP B',
    count: 4,
  }
]

const result = arrA.map(aObj => {
    const matchedObj = arrB.find(bObj => aObj.id === bObj.id)
    return matchedObj ? {...aObj, ...matchedObj} : aObj
})

console.log(result)
© www.soinside.com 2019 - 2024. All rights reserved.