从值数组中获取经过过滤的对象数组



我试图根据我在cars数组中的值过滤inventory数组。当前我得到的结果是[]

const cars = ['s', 'y']
const inventory = [{
desc: 'Tesla',
customers: [{
model: 's',
name: 'John'
}]
}, {
desc: 'Audi',
customers: [{
model: 'q3',
name: 'Doe'
}]
}]
const result = inventory.filter((val) => {
cars.includes(val.customers.map((val) => val.model))
})
console.log(result)

我期待的结果如下。有人能帮忙吗?

[{
desc: 'Tesla',
customers: [{
model: 's',
name: 'John'
}]
}]

问题是filter()函数。includes()中的map()函数返回一个数组,因此您需要使用some()函数来检查是否有任何客户模型与cars数组匹配。

const cars = ['s', 'y']
const inventory = [{
desc: 'Tesla',
customers: [{
model: 's',
name: 'John'
}]
}, {
desc: 'Audi',
customers: [{
model: 'q3',
name: 'Doe'
}]
}]
const result = inventory.filter((val) => {
return val.customers.some((customer) => cars.includes(customer.model))
})
console.log(result)

您可以使用filterreduceincludes:

const cars = ['s', 'y']
const inventory = [{
desc: 'Tesla',
customers: [{
model: 's',
name: 'John'
}]
}, {
desc: 'Audi',
customers: [{
model: 'q3',
name: 'Doe'
}]
}]
const result = inventory.filter((item) =>
item.customers.reduce((acc, curr) => acc || cars.includes(curr.model), false))
console.log(result)

相关内容

  • 没有找到相关文章

最新更新