如何使用另一个array
过滤某些属性,如果匹配条件,它将返回另一个属性,例如:
Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}]
Array2 = [{id:0, offenceCode: 'JLN14'}, {id:1, offenceCode: 'JLN13'}]
首先,我得到Array2
并将属性offenceCode
与Array1
进行比较,如果属性相同,Array1
应该返回OffenceDesc
这是我尝试过的:
demo = [
{
offenceCode: 'JLN14',
offenceType: '7',
offenceDesc: 'emergency lane abuse'
},
{
offenceCode: 'BRG04',
offenceType: '8',
offenceDesc: 'speeding'
},
{
offenceCode: 'CRG04',
offenceType: '9',
offenceDesc: 'emergency lane abuse'
}
];
offenceCode: any;
ngOnInit() {
this.offenceCode = this.items.map(x => x.offenceCode1);
console.log(this.offenceCode);
if(this.demo.forEach(x => x.offenceCode === this.offenceCode)) {
// return offenceDesc
}
}
目前我不知道如何解决这个问题,这是我的stackblitz demo,我可以就如何解决这个问题使用任何建议,如果有更好的实践,谢谢
答案 0 :(得分:1)
您可以使用Array.prototype.findIndex进行此操作。
const matchIndex = this.demo.findIndex(x => x.offenceCode === this.offenceCode);
if(matchIndex !== -1) {
return this.demo[matchIndex].offenceDesc;
}
return undefined;
请注意,findIndex
如果找不到匹配项,将返回-1。
答案 1 :(得分:1)
看起来您正在寻找:
offenceCode: string[];
ngOnInit() {
this.offenceCode = this.items.map(x => x.offenceCode1);
this.demo.forEach(x => {
this.offenceCode
.filter(e => e === x.offenceCode)
.forEach(e => console.log(x.offenceDesc));
});
}
进行以下修改:
offenceCode
定义为字符串[] demo
数组并在上一行的 offenceCode 上执行过滤器。现在,满足条件的任何内容都会记录到控制台中(您可以根据需要进行更改)答案 2 :(得分:0)
ngOnInit(){
let Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}]
let Array2 = [{id:0, offenceCode: 'JLN14'}, {id:1, offenceCode: 'JLN13'}]
let object = Array1.filter(x => x.offenceCode == Array2.filter(y => y.offenceCode == x.offenceCode)[0].offenceCode)[0]
return object ? object.offenceDesc ? null
}