[英]How to compare and filter two different JS objects that one to many relationship
I have two different JS objects and I want to compare and filter them, like I need to compare clusters with pathways and finally clusters must be only that are mapped to pathways.我有两个不同的 JS 对象,我想比较和过滤它们,就像我需要比较集群和路径一样,最后集群必须只是映射到路径的。
const pathways = [{area: 1, clusterId: 1},{area: 2, clusterId: 4}];
const clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];
And expected result when I print cluster is [{id:1,name:'london'}, {id:4, name: 'brussel'}].我打印集群时的预期结果是 [{id:1,name:'london'}, {id:4, name: 'brussel'}]。
Here is what I tried这是我试过的
let pathways = [{id: 1, clusterId: 1},{id: 2, clusterId: 4}];
let clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];
clusters = clusters.filter((cluster, i) => {
if (cluster.id === pathways[i].clusterId) {
return clusters;
}
});
console.log(clusters);
But I am getting Error: Cannot read properties of undefined (reading 'clusterId'), can some help me?但是我收到错误:无法读取未定义的属性(读取“clusterId”),有人可以帮我吗?
What I tried我试过的
let pathways = [{id: 1, clusterId: 1},{id: 2, clusterId: 4}];
let clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];
clusters = clusters.filter((cluster, i) => {
if (cluster.id === pathways[i].clusterId) {
return clusters;
}
});
console.log(clusters);
And what I expect cluster = [{id:1,name:'london'}, {id:4, name: 'brussel'}].我期望 cluster = [{id:1,name:'london'}, {id:4, name: 'brussel'}]。
Two lists = two loops两个列表 = 两个循环
const pathways = [{area: 1, clusterId: 1},{area: 2, clusterId: 4}]; const clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}]; const filtered = clusters.filter(cluster => pathways.some(pathway => pathway.clusterId === cluster.id)) console.log(filtered)
let cluster2 = [];
clusters.forEach((item)=>{
pathways.forEach((subItem)=>{
if(item.id == subItem.clusterId){
cluster2.push(item);
}
})
});
console.log(cluster2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.