在 JS 中过滤具有深度嵌套数组的数组 [英] Filtering an array with a deeply nested array in JS
本文介绍了在 JS 中过滤具有深度嵌套数组的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何过滤具有深度嵌套数组的数组?给定以下 2 个数组,我需要结果是一个只有 rice cakes
和 gluten-free-pizza
对象的数组:
How can I filter an array with a deeply nested array? Given the following 2 arrays, I need the result to be an array with only the rice cakes
and the gluten-free-pizza
objects:
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 个对象)的方法:
I tried the following which just returns everything (the 4 objects):
var result = foodsAvailable.filter(function(food) {
return foodsILike.filter(function(foodILike) {
return foodILike === food;
})
})
result
// Array [ Object, Object, Object, Object]
推荐答案
你可以使用 Array#some
和 Array#includes
用于检查 foodILike 是否包含标签.
You could use Array#some
and Array#includes
for checking if foodsILike contains a tag.
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; }
这篇关于在 JS 中过滤具有深度嵌套数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文