【问题标题】:Filter an array<objects> by two other array<strings>通过另外两个数组<strings> 过滤一个数组<objects>
【发布时间】:2017-06-12 01:38:23
【问题描述】:

我有一个简短的问题:

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

我的数组如下所示:

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

【问题讨论】:

  • 第一个数组的类型定义是什么?
  • 目前是 ,但我稍后会添加。

标签: arrays angular typescript ionic2


【解决方案1】:

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

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

【讨论】:

  • 哦,太好了,这很容易!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多