通过另外两个数组<strings>过滤数组<objects>

时间:2017-01-26 14:38:05

标签: arrays angular typescript ionic2

我有一个简短的问题:

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

My Array看起来像这样:

[
  {
    "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
    }>
}

1 个答案:

答案 0 :(得分:2)

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

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;
});