我试图根据我在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)
您可以使用filter
与reduce
和includes
:
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)