【发布时间】: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 && match.win && match.win.user && match.win.user.name && match.win.user.name.match(regex) -
感谢您的回答。但是,它仍然不起作用。
标签: javascript regex reactjs filter redux