简体   繁体   中英

What is the best way to perform a RegEx test over multiple model fields?

If I have the following model:

data = [
  {comment: 'Blue eyes', label: 'Red', User: 'John Doe', total: 345},
  {comment: 'Bye', label: 'Blue', User: 'Jane Doe', total: 497},
  {comment: 'Whatever', label: 'Green', User: 'Blues Saraceno', total: 987}
]

And I need to filter the results from an existing filterString . Eg 'blue' What is the best way to apply:

const filterRegex = new RegExp(filterString, 'i')

To all of the model fields? No mmater if the sting is in the comment, user, label or total ?

I really appreciate any help. Thanks

This algorithm will filter both the array and the objects inside the array. Will look for a REGEXP match inside all of the values in your objects an will return an array of the objects that at least had on matching value

Hope this helps :)

 var data = [ {comment: 'Blue eyes', label: 'Red', User: 'John Doe', total: 345}, {comment: 'Bye', label: 'Red', User: 'Jane Doe', total: 497}, {comment: 'Whatever', label: 'Green', User: 'Blues Saraceno', total: 987} ] const filterRegex = new RegExp('blue', 'i') var newA = data.filter(el=>{ let filterd = Object.values(el).filter(el=> el.toString().match(filterRegex) != null) if(filterd.length != 0) return el }) console.log(newA) 

The logic will need to check every object but since only one value needs to match the filter string then it only needs to match one of the values (ie there is no need to check every value if a match already occurred). This can be accomplished with using the native Array method of filter for removing non-matching objects and some for matching only once per set of object values.

The function would look like something like this:

function filter(filterStr, data) {
  const filterRegex = new RegExp(filterStr, 'i');

  // Iterate over data array and only return matching objects
  return data.filter((o) =>
    // Only check values until one matches
    Object.values(o).some((v) =>
      filterRegex.test(v)
    )
  );
}

And a working example:

 const data = [{ comment: 'Blue eyes', label: 'Red', User: 'John Doe', total: 345 }, { comment: 'Bye', label: 'Blue', User: 'Jane Doe', total: 497 }, { comment: 'Whatever', label: 'Green', User: 'Blues Saraceno', total: 987 } ]; function filter(filterStr, data) { const filterRegex = new RegExp(filterStr, 'i'); // Iterate over data array and only return matching objects return data.filter((o) => // Only check values until one matches Object.values(o).some((v) => filterRegex.test(v) ) ); } console.log(filter('Blue', data)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM