javascript - 在 React.js 中使用正则表达式过滤数组?

标签 javascript regex reactjs

我希望能够检查并查看哪些键以字母“gra”开头,并且仅返回该内容。我用下面的代码尝试了一些事情。在一种方法中,我在返回 html 中添加了类似 {key.match(/gra/g)} 的内容,但它不是很有效(并且仍然输出空白内容)。我也尝试过添加这样的内容:

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

也尝试过:

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

但不断收到“.match”不是函数或无法读取未定义等错误。我尝试了各种其他方法,但似乎无法使其正常工作。

   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>

那么,综上所述,使用正则表达式过滤此类内容的最佳方法是什么?

最佳答案

为什么不直接过滤数组

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

关于javascript - 在 React.js 中使用正则表达式过滤数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34949789/

相关文章:

android - 使用 React-Native 在 android 中捕获 RECEIVE_BOOT_COMPLETED 事件

reactjs - react : Don't render components in table who aren't visible

javascript - Jquery getJson 页面永远不会完成加载

.net core webapi路由属性正则表达式与/

mysql - 使用 MySql REGEX 从包含一位或两位数字的字符串中仅获取一位数字

javascript - Flowtype 不检查导入的 redux 容器上的 Prop

Javascript 等待在异步函数中不被尊重

javascript - 除以 0 和 0.00

javascript - 剑道 UI 下拉列表 : how add new elements dynamically

javascript - 正则表达式 在分号之前添加 !important (如果不存在)