javascript 如何比较和过滤两个不同的JS对象的一对多关系

kdfy810k  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(151)

我有两个不同的JS对象,我想比较和过滤它们,就像我需要比较集群和路径一样,最后集群必须只Map到路径。

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'}];

打印群集时的预期结果为[{id:1,name:“伦敦”},{id:4,name:'布鲁塞尔'}]。
以下是我尝试的方法

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);

但我收到错误:无法读取未定义的属性(阅读“clusterId”),需要帮助吗?
我所尝试的

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);

我期望的是cluster = [{id:1,name:“伦敦”},{id:4,name:“brussel”}]。

aiqt4smr

aiqt4smr1#

两个列表=两个循环

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)
flvlnr44

flvlnr442#

let cluster2 = [];
 clusters.forEach((item)=>{
  pathways.forEach((subItem)=>{
    if(item.id == subItem.clusterId){
      cluster2.push(item);
    }
  })
 });
console.log(cluster2);

相关问题