如何过滤带有深层嵌套数组的数组?给定以下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; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句