我有2个array
:
items = [
{
offenceType:"7",
offenceCode:"JLN14",
},
{
offenceType:"48",
offenceCode:"JLN14",
}
];
demo = [
{
offenceCode: 'JLN14',
offenceType: '7',
offenceDesc: 'emergency lane abuse'
},
{
offenceCode: 'JLN14',
offenceType: '48',
offenceDesc: 'speeding'
},
{
offenceCode: 'JLN13',
offenceType: '52',
offenceDesc: 'parking abuse'
}
];
如何在这2个array
之间过滤一些属性,例如:
在items
中得到了offenceType
和OffenceCode
,因此我需要将其与包含demo
,offenceType
和offenceCode
的{{1}}进行比较,如果offenceDesc
和offenceType
是匹配项,根据我在Google上搜索的内容,我需要从offenceCode
中获取offenceDesc
,
demo
这是我的stackblitz demo
以前我曾经问过类似prev question的问题,但是尽管尝试了很多次如何解决这个问题,但我还是无法弄清楚,我是编码新手,希望有人可以提出解决问题的建议< / p>
答案 0 :(得分:0)
您可以使用地图
const items = [
{
offenceType:"7",
offenceCode:"JLN14",
},
{
offenceType:"48",
offenceCode:"JLN14",
}
];
const demo = [
{
offenceCode: 'JLN14',
offenceType: '7',
offenceDesc: 'emergency lane abuse'
},
{
offenceCode: 'JLN14',
offenceType: '48',
offenceDesc: 'speeding'
},
{
offenceCode: 'JLN13',
offenceType: '52',
offenceDesc: 'parking abuse'
}
];
const newArray = items.map(item => {
const lookup = demo.find(i => item.offenceType === i.offenceType);
return {
offenceType: lookup.offenceType,
offenceCode: lookup.offenceCode,
offenceDesc: lookup.offenceDesc
}
});
console.log(newArray);
答案 1 :(得分:0)
您可以定义一个查找犯罪描述的函数,然后在具有该函数的项目上使用地图
const items = [
{
offenceType:"7",
offenceCode:"JLN14",
},
{
offenceType:"48",
offenceCode:"JLN14",
}
];
function findOffenseDesc(item) {
const demo = [
{
offenceCode: 'JLN14',
offenceType: '7',
offenceDesc: 'emergency lane abuse'
},
{
offenceCode: 'JLN14',
offenceType: '48',
offenceDesc: 'speeding'
},
{
offenceCode: 'JLN13',
offenceType: '52',
offenceDesc: 'parking abuse'
}
];
const match = demo.find(offense => offense.offenceCode === item.offenceCode && offense.offenceType === item.offenceType);
return match && match.offenceDesc;
}
const newArray = items.map(findOffenseDesc);
console.log(newArray); // [ "emergency lane abuse", "speeding" ]
答案 2 :(得分:0)
您还可以使用过滤器和地图。假设您只需要犯罪即可
const offenceDescriptions = demo.filter(
d => items.find(item => item.offenceCode === d.offenceCode
&& item.offenceType === d.offenceType))
.map(x => x.offenceDesc)
答案 3 :(得分:0)
您可以通过every()
方法使用取反逻辑。
相关代码:
...
newArray = [];
constructor() { }
ngOnInit() {
let foundOffence: any;
this.items.forEach(itemsOffence => {
this.demo.every(demoOffence => {
let isNoMatch: boolean = demoOffence.offenceCode != itemsOffence.offenceCode || demoOffence.offenceType != itemsOffence.offenceType;
foundOffence = isNoMatch? undefined: demoOffence;
return isNoMatch;
})
if (foundOffence) {
console.log(`foundOffenceDesc = ${foundOffence.offenceDesc}`);
this.newArray.push(foundOffence);
}
})
console.log("newArray = ", this.newArray);
}
...
您可以看到它在此StackBlitz demo
中工作