filter object by key values

19,708

Solution 1

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

Solution 2

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)

Share:
19,708
slawckaJS
Author by

slawckaJS

learning javascript

Updated on June 04, 2022

Comments

  • slawckaJS
    slawckaJS almost 2 years

    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.

  • Jeff Bluemel
    Jeff Bluemel over 3 years
    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().includ‌​es(searchText.toLowe‌​rCase()));