我有两个不同的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”}]。
2条答案
按热度按时间aiqt4smr1#
两个列表=两个循环
flvlnr442#