Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading