slawckaJS
slawckaJS

Reputation: 61

filter object by key values

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

Answers (2)

Emeeus
Emeeus

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

Ankit Agarwal
Ankit Agarwal

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

Related Questions