从数组中过滤对象数组

时间:2020-03-23 18:26:11

标签: javascript arrays

我有一个对象数组lookups和一个数组filters。现在,我想使用对象属性name从对象数组中过滤出数组。

我使用了filtersome,但没有得到预期的结果。

预期结果:

[{id: 3, name: "Linkedin"}]

let lookups = [
{id: 1, name: "Twitter"},
{id: 2, name: "Facebook"},
{id: 3, name: "Linkedin"}
]

let filters = ["Facebook", "Twitter"]

const filtered = lookups.filter(lookup => filters.some(filter => filter.toLowerCase() != lookup.name.toLowerCase()));

console.log(filtered)

1 个答案:

答案 0 :(得分:3)

您的代码给出的结果元素中,filters中的某些值不等于元素的name。因此,对于每个元素,某些名称都不相同。

换句话说,您将!=||一起使用,它将始终返回true

let a = "anything";
console.log(a !== "thing1" || a !== "thing2")

您需要使用every()而不是some()

let lookups = [
{id: 1, name: "Twitter"},
{id: 2, name: "Facebook"},
{id: 3, name: "Linkedin"}
]

let filters = ["Facebook", "Twitter"]

const filtered = lookups.filter(lookup => filters.every(filter => filter.toLowerCase() !== lookup.name.toLowerCase()));

console.log(filtered)