Reputation: 61
I have an array of objects lets say:
var ob=[
{
name:'john',
surname:'fox'
}, {
name:'jill',
surname:'hog'
}
];
I'm implementing search on a website, where i can input either name or surname, and it should filter new array by objects that contain input value.
So if my input is 'fox' it will filter out the object that contains key value 'fox'
my simple idea was :
ob.filter(item=>{ return item.name.includes(searchterm) ||
item.surname.includes(searchterm)}
But i guess there are better ways, in case key names change.
Upvotes: 3
Views: 24974
Reputation: 5250
If you are searching only in values, you could use Object.values()
inside filter()
, and includes()
to find if the input is in the array of values.
var ob=[{name:'john', surname:'fox'},{name:'jill',surname:'hog'}];
let input = 'fox';
var res = ob.filter(o=>Object.values(o).includes(input))
console.log(res)
Upvotes: 6
Reputation: 30739
You can loop over the keys of the inner object so that doing so you can use Array.some()
to get the match of the searched text. It will work for any number of keys of any name so you do not need to get depend on the keys name
and surname
.
var ob = [{
name: 'john',
surname: 'fox'
},
{
name: 'jill',
surname: 'hog'
}
];
var searchText = 'fox';
var res = ob.filter((item)=>{
return Object.keys(item).some((key)=>item[key].includes(searchText));
});
console.log(res);
Upvotes: 8