【发布时间】:2019-04-03 21:02:30
【问题描述】:
当我有两个大对象并且必须在过滤过程中比较它们时,我在使用 javascript 中的过滤方法时遇到了一些问题。
为简单起见,我创建了一个示例,其中我们有两个数组:array_1 和 array_2。
Array_2 应根据 array_1 中存在的 id 进行过滤。 (这些 id 在每个数组中都是相同的)
let array_1 = [
{ id: '_i23455szq', description: 'text' },
{ id: '_h6yf2uk1n', description: 'text' }
]
let array_2 = [
{ id: '_h6yf2uk1n', description: 'text', capacity: 2 },
{ id: '_465324423', description: 'text', capacity: 4 },
{ id: '_i23455szq', description: 'text', capacity: 0 },
{ id: '_54234gfgd', description: 'text', capacity: 0 },
]
如您所见,在 array_2 中我们有一个容量集。我正在尝试根据容量进行过滤,我想过滤array_2,所以在过滤后,它包括每个具有容量的对象(大于0,但也包括与array_1中的一次匹配的对象)
如果您应该在没有太多 for 循环的情况下制定一个不错的解决方案,如何做到这一点?
这甚至可以在 1-2 行中实现吗?
已尝试在内部使用过滤和 forEach,但似乎无法创建一个不占用太多空间的解决方案。
array_2 = array_2.filter(function (i) {
array_1.forEach(j => {
if (j.id == i.id) {
console.log("ID matches")
// How to return??
}
})
})
输出应该是以下对象:
{ id: '_h6yf2uk1n', description: 'text', capacity: 2 },
{ id: '_465324423', description: 'text', capacity: 4 },
{ id: '_i23455szq', description: 'text', capacity: 0 },
【问题讨论】:
-
为什么包含第二个对象,id
_465324423不在第一个数组中? -
因为它的容量大于 0 ,所以如果一个从 arrarray_1 匹配但容量为 0 的,它也应该包括在内。
-
啊,所以条件是or,而不是and,明白了
标签: javascript arrays sorting filtering