<objects> 按另外两个数组筛选数组<strings>



我有一个简短的问题:

我想通过两个字符串数组过滤对象数组。

我的数组如下所示:

[
  {
    "id": 12345,
    "title": "Some title",
    "contains": [
      {
        "slug": "fish",
        "name": "Fish"
      }, {
        "slug": "soy", // search term, like a id
        "name": "Soy"
      } 
    ], "complexity": [
      {
        "slug": 4, // search term, like a id
        "name": "hard"
      }, {
}],..
      },
{...}

这是我的两个数组:

// recipes should not contain this ingredients
let excludedIngredientsArray = Array<string> = ["soy", "fish"]; 
// recipes should not contain this complexities
let excludedComplexityArray = Array<string> = [1, 2];

现在我想通过这两个数组过滤食谱,并想删除所有包含排除术语的食谱

最好的

方法是什么?

多谢!

编辑:

recipeArray 看起来像这样:

interface recipeArray {
    reciepe: Array<{
        name: string,
        contains: Array<{slug: string, name: string}> //Ingredients array
        complexity: Array<{slug: string, name: string}> //complexity array
    }>
}

如果你的第一个数组是这样的:

interface Item {
    id: number;
    title: string;
    contains: { slug: string; name: string }[],
    complexity: { slug: number; name: string }
}
let data: Item[];

然后,您可以像这样拥有所需的过滤数组:

let excluded = data.filter(item => {
    return item.contains.every(obj => excludedIngredientsArray.indexOf(obj.slug) < 0)
        && excludedComplexityArray.indexOf(item.complexity.slug) < 0;
});

相关内容

  • 没有找到相关文章

最新更新