Michael Sebastian
Michael Sebastian

Reputation: 785

Filter array using regex in React.js?

I want to be able to check and see which keys start with the letters "gra" and only return that content. I've tried a few things with the code below. In one approach I added something like {key.match(/gra/g)} in the return html but it is not very efficient (and still outputs blank content). I've also tried adding something like this:

  if(String(this.props.profile[key]).match(/gra/g)))

also tried:

  if(this.props.profile[key].match(/gra/g))

but keep getting errors like ".match" is not a function or can't read undefined, etc. I've tried various other ways but can't seem to get it working right.

   var grapes = Object.keys(this.props.profile).map(function(key) {
        if(this.props.profile[key] !=null) {
                return (
                     <li key={key} className="example-class">
                         <label>{key}:</label>{ this.props.profile[key] }
                      </li>
                  );
              }
    }, this);


    <html>
       {grapes}
    </html>

So, all that to say, what is the best way to filter using regex for something like this?

Upvotes: 1

Views: 4934

Answers (1)

adeneo
adeneo

Reputation: 318212

Why not just filter the array

var grapes = Object.keys(this.props.profile)
                   .filter(function(key) {
                       return key && key.toLowerCase().indexOf('gra') === 0;
                   })
                   .map(function(key) {
                       return (
                         <li key={key} className="example-class">
                             <label>{key}:</label>{ this.props.profile[key] }
                         </li>
                       );
                   }, this);

Upvotes: 2

Related Questions