试图获得低于预期的结果,但没有进入specialtyMembers
的for循环中的任何想法,如何获得与两个数组匹配的预期响应,是否有使用过滤器的方法?
main.js
const members = [{
"indexId": "1",
"planId": "8304TDMACC001"
}]
const specialtyMembers = [{
"proxyId": "",
"internalID": "38482099",
"externalID": "",
"indexID": "1",
"gender": "Male"
},
{
"proxyId": "",
"internalID": "38482100",
"externalID": "",
"indexID": "2",
"gender": "Female"
}
]
if (members) {
const membersArray: any = [];
for (const member of members) {
if (specialtyMembers) {
for (const cacheMember of specialtyMembers) {
if (member.indexId === cacheMember.indexID) {
membersArray.push(cacheMember);
}
}
}
}
specialtyMembers = membersArray;
}
预期的输出,因为indexId仅与此匹配
[{
"proxyId": "",
"internalID": "38482099",
"externalID": "",
"indexID": "1",
"gender": "Male"
}
]
答案 0 :(得分:1)
通过filter
数组specialtyMembers
就像这样:
specialtyMembers = specialtyMembers.filter(e => members[0].indexId == e.indexID);
注意:您必须将specialtyMembers
从常量更改为变量。为此,请在此行中将const
更改为var
:
var specialtyMembers = [{...}, {...}];
演示:
const members = [{
"indexId": "1",
"planId": "8304TDMACC001"
}];
var specialtyMembers = [{
"proxyId": "",
"internalID": "38482099",
"externalID": "",
"indexID": "1",
"gender": "Male"
},
{
"proxyId": "",
"internalID": "38482100",
"externalID": "",
"indexID": "2",
"gender": "Female"
}
];
specialtyMembers = specialtyMembers.filter(e => members[0].indexId == e.indexID);
console.log(specialtyMembers);
如果members
中有多个元素,则只需要像这样创建indexId
的数组即可:
var indexIds = members.map(e => e.indexId);
然后将filter
语句更改为此:
specialtyMembers = specialtyMembers.filter(e => indexIds.includes(e.indexID));
演示:
const members = [{
"indexId": "1",
"planId": "8304TDMACC001"
}];
var specialtyMembers = [{
"proxyId": "",
"internalID": "38482099",
"externalID": "",
"indexID": "1",
"gender": "Male"
},
{
"proxyId": "",
"internalID": "38482100",
"externalID": "",
"indexID": "2",
"gender": "Female"
}
];
var indexIds = members.map(e => e.indexId);
specialtyMembers = specialtyMembers.filter(e => indexIds.includes(e.indexID));
console.log(specialtyMembers);
答案 1 :(得分:0)
使用reduce
可以使用filter
使用specialtyMembers = members.reduce((acc, ele) => {
const filteredArr = specialtyMembers.filter(x => ele.indexId === x.indexID)
return filteredArr.length > 0 ? acc.concat(filteredArr) : acc;
}, [])
创建一个新数组,其中只有在您的条件下通过的元素:
sap.m.Input
答案 2 :(得分:0)
const members = [{
"indexId": "1",
"planId": "8304TDMACC001"
}]
const specialtyMembers = [{
"proxyId": "",
"internalID": "38482099",
"externalID": "",
"indexID": "1",
"gender": "Male"
},
{
"proxyId": "",
"internalID": "38482100",
"externalID": "",
"indexID": "2",
"gender": "Female"
}
]
if (members) {
let memberIndexes = new Set(members.map(m => m.indexId))
let result = specialtyMembers ? specialtyMembers.filter(m => memberIndexes.has(m.indexID)) : []
console.log(result)
}