-1

I have an array like this

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

Now, for example, I want to return an array that contains the word book

I have tried the following but failed -

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

I also tried this but it returned the first matching result instead of all matching results -

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

Please help with a solution that can yield an array with all items that match the filter condition/s.

shripal mehta
  • 401
  • 4
  • 21

2 Answers2

3

The below code will work as you expected. This checks the word 'Book' is present in the Array of object and return the particular object.

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);
Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
  • filter should return true or false. works because return "something" or null, but you can directly:`let newArr = pro.filter(item=>{return item.name.indexOf('book') > -1}})` – Eliseo Nov 28 '22 at 08:24
2

Try this let test = b.filter((s)=>s.name.includes('book'));

Reaper
  • 402
  • 3
  • 13
  • that just return one result i dont know why – Majid Maddah Nov 28 '22 at 06:21
  • if your array is [{ "id": 1, "name": "this is book", },{ "id": 2, "name": "this is a test book", },{ "id": 3, "name": "this is a desk", }] this then its return two value – Reaper Nov 28 '22 at 06:38