如果数组有匹配的 id 将对象更改为一个对象而不影响原始数组,使用下面的代码它只返回匹配的对象,但我想要预期的结果如前所述
主要.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;
}, []);
关于javascript - 如何从数组中获取匹配元素并更改数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53659950/