【问题标题】:how to filter array that contain a word如何过滤包含单词的数组
【发布时间】:2022-11-28 14:38:37
【问题描述】:

我有一个这样的数组

{
    "id": 1,
    "name": "this is book",
}

{
    "id": 2,
    "name": "this is a test book",
}

{
    "id": 3,
    "name": "this is a desk",
}

过滤数组时,我想返回示例中包含书籍的数组

我试过了

   let test = this.pro.filter((s: { name: any; })=>s.name===book); 

不在搜索中工作 并尝试

 let test = this.pro.filter((s: { name: any; })=>s.name===this is book); 

工作但只返回 id 1 它应该返回 id 1 & 2

任何解决方案 谢谢;

【问题讨论】:

标签: angular typescript


【解决方案1】:

下面的代码将按您的预期工作。这会检查对象数组中是否存在单词“Book”并返回特定对象。

const pro = [
{
"id": 1,
"name": "this is book",
},
{
"id": 2,
"name": "this is a test book",
},
{
"id": 3,
"name": "this is a desk",
}]

let newArr = pro.filter(item=>{
  if(item.name.indexOf('book') > -1){
    return item;
  }
})
console.log(newArr);

【讨论】:

  • 伙计,你救救我吧,我在那个 thanx 兄弟上工作了四个小时;)
【解决方案2】:

试试这个let test = b.filter((s)=>s.name.includes('book'));

【讨论】:

  • 只返回一个结果我不知道为什么
猜你喜欢
  • 1970-01-01
  • 2019-05-11
  • 2019-06-16
  • 2020-02-18
  • 2018-08-07
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
相关资源
最近更新 更多