对象数组中的过滤器数组

时间:2020-04-10 02:26:17

标签: javascript arrays filter

我有这个数组:

[
  {
    "title": "fruit",
    "categories": [
      "apple",
      "banana"
    ]
  },
  {
    "title": "city",
    "categories": [
      "Brazil",
      "EUA",
      "China"
    ]
  },
  {
    "title": "name",
    "categories": [
      "Ana"
    ]
  }
]

我想通过用户键入的任何字词对此进行过滤

我已经知道了,仅适用于标题,但我想按标题和类别进行搜索:

array.filter(f => f.title.includes(myString))

3 个答案:

答案 0 :(得分:3)

||上的.some来代替f.categories

array.filter(f =>
  f.title.includes(myString) ||
  f.categories.some(
    category => category.includes(myString)
  )
);

现场演示:

const array = [
  {
    "title": "fruit",
    "categories": [
      "apple",
      "banana"
    ]
  },
  {
    "title": "city",
    "categories": [
      "Brazil",
      "EUA",
      "China"
    ]
  },
  {
    "title": "name",
    "categories": [
      "Ana"
    ]
  }
];

const input = document.querySelector('input');
input.addEventListener('input', () => {
  document.querySelector('div').textContent = JSON.stringify(
    array.filter(f =>
      f.title.includes(input.value) ||
      f.categories.some(
        category => category.includes(input.value)
      )
    )
  );
});
<input>
<div></div>

这不是您的原始代码实现的逻辑,但是如果您还需要检查不同的大小写匹配,则:

const array = [
  {
    "title": "fruit",
    "categories": [
      "apple",
      "banana"
    ]
  },
  {
    "title": "city",
    "categories": [
      "Brazil",
      "EUA",
      "China"
    ]
  },
  {
    "title": "name",
    "categories": [
      "Ana"
    ]
  }
];

const input = document.querySelector('input');
input.addEventListener('input', () => {
  const value = input.value.toLowerCase();
  document.querySelector('div').textContent = JSON.stringify(
    array.filter(f =>
      f.title.toLowerCase().includes(value) ||
      f.categories.some(
        category => category.toLowerCase().includes(value)
      )
    )
  );
});
<input>
<div></div>

答案 1 :(得分:1)

如果您只想要与标题和类别匹配的项目,则可以执行此操作以获取匹配项数组。

array.filter(f => f.title === 'myTitle' && f.categories.includes('myCategory'));

答案 2 :(得分:1)

如果您只想按标题或类别进行过滤,我认为这已经足够了

const array = [
  {
    "title": "fruit",
    "categories": [
      "apple",
      "banana"
    ]
  },
  {
    "title": "city",
    "categories": [
      "Brazil",
      "EUA",
      "China"
    ]
  },
  {
    "title": "name",
    "categories": [
      "Ana"
    ]
  }
]

const string = 'Brazil'// whatever the user types

const result = array.filter(f => f.title === string || f.categories.includes(string))
console.log(result);