如果数组具有匹配的ID,则将对象更改为一个对象,而不用下面的代码影响原始数组,则它仅返回匹配的对象,但我希望得到如上所述的预期结果
main.ts
const arr = [{
"body": {
"specialtyID": "7114798",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "00445450085",
"rxNumber": "14678904"
}]
},
{
"body": {
"specialtyID": "7114798",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "00004080085",
"rxNumber": "1459004"
}]
}
},
{
"body": {
"specialtyID": "7908398",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "06789955085",
"rxNumber": "1478604"
}]
}
}
]
const tempArray = arr;
function arrayMatch(temp, arr) {
const finalArray = [];
arr.forEach((element) => {
tempArray.forEach((temp) => {
if (temp.speicaltyID === element.specialtyID) {
temp.rxInfos.forEach((rxInfo) => {
element.rxInfos.push(rxInfo);
});
}
}
finalArray = arr;
});
return finalArray
}
预期输出
const arr = [{
"body": {
"specialtyID": "7114798",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "00445450085",
"rxNumber": "14678904"
},
{
"drugNdc": "00004080085",
"rxNumber": "1459004"
}
]
},
{
"body": {
"specialtyID": "7908398",
"sourceSystem": "HBS",
"rxInfos": [{
"drugNdc": "06789955085",
"rxNumber": "1478604"
}]
}
}
]
答案 0 :(得分:2)
您可以尝试使用此方法来获得所需的结果:
const result = arr.reduce((container, value) => {
const compare = ({ body }) => body.specialtyID === value.body.specialtyID;
const isExists = container.some(compare);
const pushRxInfos = container.map(item => compare(item) ? item.body.rxInfos.push(...value.body.rxInfos) : item);
isExists ? pushRxInfos : container.push(value);
return container;
}, []);