在JS中使用深度嵌套的数组过滤数组

傻瓜

如何过滤带有深层嵌套数组的数组?给定以下2个数组,我需要将结果设置为仅包含rice cakesgluten-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]
妮娜·斯科茨(Nina Scholz)

您可以使用Array#someArray#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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章