reactjs 解构Regex组时未定义的属性

neskvpey  于 2023-10-17  发布在  React
关注(0)|答案(1)|浏览(132)

我正在解析一个包含组的regEx。在JavaScript中,我试图将match.groups分解为变量并获得TypeError: Cannot read property 'familyName' of undefined, js engine: hermes
以下是React Native中的代码片段,我正在尝试用途:

const parseCode = data => {
    const payload = {};
    for (const match of data.matchAll(rgx)) {
      const {familyName, givenName, birthday} =
        match.groups;
      
      console.log(
        `familyName: ${familyName}  givenName:${givenName}  birthday: ${birthday}`);
    }
};

如何确保给予空值?
谢谢你,谢谢!

anhgbhbe

anhgbhbe1#

试试这个代码:

const parseCode = data => {
    const rgx = /your-regex-pattern/g;
    
    const payload = Array.from(data.matchAll(rgx), ({ groups }) => ({
        familyName: groups?.familyName || null,
        givenName: groups?.givenName || null,
        birthday: groups?.birthday || null
    }));

    console.log(payload);
};

这提供了对匹配的紧凑且高效的处理,同时确保缺失组的回退值为null。

相关问题