Search code examples
javascriptobjectsearchmethodsjavascript-objects

How to dynamically grab object keys and use the keys as part of a method?


I would like to create the filter function to dynamically search through each key for the user search results. How can I do this without hardcoding each key.

const data = [
  { title: "title1", body: "body1", footer: "footer1" },
   { title: "title2", body: "body2", footer: "footer2" },
   { title: "title3", body: "body3", footer: "footer3" },
];

const search = 'footer1'

 const filter = data.filter(
      (item) => item.title.includes(search) || item.body.includes(search) || item.footer.includes(search)
    );


Solution

  • For each object that you loop over in the .filter() callback, you can grab all of its values using Object.values(), then you can use .some() on this array to check if any of the values within this array contain the search string:

    const data = [ { title: "title1", body: "body1", footer: "footer1" }, { title: "title2", body: "body2", footer: "footer2" }, { title: "title3", body: "body3", footer: "footer3" }, ];
    
    const search = 'footer1';
    const filter = data.filter(
      (item) => Object.values(item).some(val => val.includes(search))
    );
    console.log(filter);