【问题标题】:Filtering a objects in objects for ReactJS为 ReactJS 过滤对象中的对象
【发布时间】:2019-12-16 20:28:59
【问题描述】:

我试图过滤对象值。但是,我不知道如何处理要过滤的对象值中的对象。例如,我想查找包含名为 James 的用户姓名值的特定数据,他是获胜者。我尝试使用“match.win.user.name.match(regex)”。它不起作用。请帮我。谢谢。

    case FILTER_MATCH:
      return {
        ...state,
        filtered: state.matches.filter(match => {
          const regex = new RegExp(`${action.payload}`, 'gi');
          return (
            match.date.match(regex) ||
            match.game.match(regex) ||
            match.win.user.name.match(regex) <-- error!
          );
        })
      };



    object match: {
    matches: [
      {
        _id: '5d4d0796b60bd206cc8e72d8',
        win: [
          {
            _id: '5d4d0796b60bd206cc8e72d9',
            user: {
              _id: '5d4942777a26a8df93097ef5',
              name: 'james',
              email: 'james@gmail.com'
            }
          }
        ],
        lose: [
          {
            _id: '5d4d0796b60bd206cc8e72da',
            user: {
              _id: '5d4942ea7a26a8df93097ef6',
              name: 'rob',
              email: 'rob@gmail.com'
            }
          }
        ],
        draw: [],
        game: 'Tic-Tac-Toe',
        date: '2019-08-09T05:41:42.494Z',
        __v: 0
      },


Error message

Unhandled Rejection (TypeError): Cannot read property 'name' of undefined
(anonymous function)
src/reducers/match.js:42
  39 | ...state,
  40 | filtered: state.matches.filter(match => {
  41 |   const regex = new RegExp(`${action.payload}`, 'gi');
> 42 |   return (
     | ^  43 |     match.date.match(regex) ||
  44 |     match.game.match(regex) ||
  45 |     match.win.user.name.match(regex)

【问题讨论】:

  • 在访问嵌套属性之前,您需要检查属性是否存在,即match &amp;&amp; match.win &amp;&amp; match.win.user &amp;&amp; match.win.user.name &amp;&amp; match.win.user.name.match(regex)
  • 感谢您的回答。但是,它仍然不起作用。

标签: javascript regex reactjs filter redux


【解决方案1】:

您访问的用户不正确。通过调用 match.win.user,您尝试从 win 访问对象用户,但如您的数据对象中所见,win 是一个包含一个用户对象的数组。如果您删除用户周围的 [] 括号,它应该可以工作。

 win: [
      {
        _id: '5d4d0796b60bd206cc8e72d9',
        user: {
          _id: '5d4942777a26a8df93097ef5',
          name: 'james',
          email: 'james@gmail.com'
        }
      }
    ]

 win: {
        _id: '5d4d0796b60bd206cc8e72d9',
        user: {
          _id: '5d4942777a26a8df93097ef5',
          name: 'james',
          email: 'james@gmail.com'
        }
      }

如果您需要将 win 作为一个数组(您应该将它们称为 wins),您可以像这样访问用户:

match.win.length !== 0 && match.win[0].user.name.match(regex)

希望这会有所帮助。

【讨论】:

  • 这是一个完美的解决方案。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 2022-12-12
  • 2019-04-19
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
相关资源
最近更新 更多