我有以下这些 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,
},
...
]
您可以按照以下方式进行:
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)