如何过滤具有深层嵌套数组的数组?给定以下 2 个数组,我需要结果是一个仅包含 rice cakes
和 gluten-free-pizza
对象的数组:
const foodsILike = ['gluten-free', 'carb-free', 'flavor-free'];
const foodsAvailable = [
{ name: 'pasta', tags: ['delicious', 'has carbs']},
{ name: 'gluten-free-pizza', tags: ['gluten-free']},
{ name: 'pizza', tags: ['delicious', 'best meal of the year']},
{ name: 'rice cakes', tags: ['flavor-free']}
]
我尝试了以下只返回所有内容(4 个对象)的方法:
var result = foodsAvailable.filter(function(food) {
return foodsILike.filter(function(foodILike) {
return foodILike === food;
})
})
result
// Array [ Object, Object, Object, Object]
最佳答案
你可以使用 Array#some
和 Array#includes
用于检查 foodsILike 是否包含标签。
const foodsILike = ['gluten-free', 'carb-free', 'flavor-free'];
const foodsAvailable = [{ name: 'pasta', tags: ['delicious', 'has carbs'] }, { name: 'gluten-free-pizza', tags: ['gluten-free'] }, { name: 'pizza', tags: ['delicious', 'best meal of the year'] }, { name: 'rice cakes', tags: ['flavor-free'] }]
var result = foodsAvailable.filter(function(food) {
return food.tags.some(function(tag) {
return foodsILike.includes(tag);
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在 JS 中过滤具有深层嵌套数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45482466/