3

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.

2 Answers 2

8

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);

1
  • This is a great solution. I added a lowercase conversion so the filtering was no longer case sensitive. return Object.keys(item).some((key)=>item[key].toLowerCase().includes(searchText.toLowerCase())); Sep 27, 2020 at 0:21
5

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.