Rox
Rox

Reputation: 19

Filter with startsWith with multiple object keys

I am making a search component and everything works well. But I have a question. How do I make the following code dynamic?

function isMatch(obj) {
  let result =  obj.code.toLowerCase().startsWith(search.toLowerCase()) || 
  obj.description.toLowerCase().startsWith(search.toLowerCase()) 
  return  result 
}

Now the search is carried out on two keys of the object, but I need to set it dynamically. For example:

serachKey = ['code', 'description', ...]

Upvotes: 0

Views: 242

Answers (1)

James
James

Reputation: 22247

Here's one approach you can try:

const searchKey = ['code', 'description'];

function isMatch(obj, search) {
  return searchKey.some(key => obj[key] && obj[key].toLowerCase().startsWith(search.toLowerCase()));
}

const mySearch = "testing";
const myObj = {"code": "some code", "description": "testing code"};

console.log(isMatch(myObj, mySearch));

Upvotes: 3

Related Questions