[英]How to get matching elements from array and change array object?
如果數組具有匹配的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"
}]
}
}
]
您可以嘗試使用此方法來獲得所需的結果:
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;
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.