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

Time:08-01

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

CodePudding user response:

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

CodePudding user response:

You can use a for...in loop to access each prop on the item object.

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) => {
      for(const prop in item){
        if(item[prop].includes(search)){
           return true
        }
    }
    return false
});

console.log(filter)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

CodePudding user response:

You can iterate all the keys(using Object.keys) inside the filter and check the value for each key.

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

const search = "filter1";

const filter = data.filter((item) => {
  for (key of Object.keys(item)) {
    if (item[key].includes(search)) {
      return item[key].includes(search);
    }
  }
});

console.log(filter);

  • Related