I have below an array called data:
const data = [
{id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: [{id:50 ,productname: 'Test A'}]},
{id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: [{id:60,productname: 'Test A'}]},
{id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: [{id:70,productname: 'Test B'}]}
]
//I have an array of objects. Inside these objects, there is another array: tags.
//My question is, how would I filter the multiple fields inside the data array
//if I filtered by, e.g., a id:1, I'd receive the following returned:
var output1 = [{id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: [{id:50 ,productname: 'Test A'}]}]
// if I filtered by, e.g., a productname: 'Test A', I'd receive the following returned:
var output2 = [ {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: [{id:50 ,productname: 'Test A'}]}, {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: [{id:60,productname: 'Test A'}]}]
//I have tried the below code but it's not working
const filter = '1';
//const filter = 'Test A';
const Result = data.filter((item) => {
return (
item.id.toString().indexOf(filter) > -1 ||item.tags.indexOf(filter) > -1
);
});
console.log(Result)