【发布时间】:2020-02-20 21:06:01
【问题描述】:
我有 3 个来源,我正在将数据提取到其中,并且只想拥有一个具有匹配对象(坐标)的项目的新集合。我尝试了几种方法,包括链接下划线方法,但似乎无法以可靠的方式提取超过 2 个。如果我使用嵌套循环,如果父循环没有匹配,它会很快变得混乱,但子循环有,它们会被错过(如果这有意义的话)。
我也尝试将它们连接到一个大数组中,如果这是最简单的方法,那会很好,但无法弄清楚如何找到坐标对象匹配。
每个数组应该有超过 20 个结果,所以性能对我来说应该不是问题。任何帮助都将不胜感激......我在不同的解决方案上花费了大量时间,我正要扔掉我的笔记本电脑。
var arrays = [
[{
id: "NMm421ue-NSXOu7Af2CNmg",
name: "name1",
source: 'mapQuest',
coords: {
lat: 35.878,
lng: -78.85
}
}, {
id: "3233e-NSXOu7A3436gdfg",
name: "another name",
source: 'mapQuest',
coords: {
lat: 40.558,
lng: -84.78
}
}],
[{
id: "1234567768",
name: 'googleName',
source: 'google',
coords: {
lat: 35.878,
lng: -78.85
}
}, {
id: "555446888",
name: 'Another Google',
source: 'google',
coords: {
lat: 44.866,
lng: -65.84
}
}],
[{
id: "54sfs2198",
name: 'Personal 1',
source: 'personal',
coords: {
lat: 44.866,
lng: -65.84
}
}, {
id: "98456245f",
name: '2nd personal',
source: 'personal',
coords: {
lat: 35.878,
lng: -78.85
}
}]
];
var result = arrays.shift().filter(function(v) {
console.log('v:', v);
return arrays.every(function(a) {
return a.indexOf(v) !== -1;
});
});
预期的结果是
[
{id: "98456245f", name:'2nd personal', source: 'personal', coords: {lat: 35.878, lng: -78.85}},
{id: "1234567768", name:'googleName', source: 'google', coords: {lat: 35.878, lng: -78.85}},
{id: "NMm421ue-NSXOu7Af2CNmg", name: "name1", source:'mapQuest', coords: {lat: 35.878, lng: -78.85}}
]
【问题讨论】:
-
我发布了一个答案,但再次阅读您的帖子,我对您到底需要什么感到有点困惑。当您说“超过两个”时,您是指
n数组中的每个(或最多两个)都有一个条目,还是只是这些欺骗出现在任何数组中,并且某些数组可能没有包含这个元素?
标签: arrays underscore.js javascript-objects