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.
CodePudding user response:
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);
CodePudding user response:
Try this let test = b.filter((s)=>s.name.includes('book'));