如何使用打字稿从 JSON 响应数组中过滤特定文本?

How to filter specific text from the JSON response array using typescript?

想要从以下其余响应中过滤一些特定文本

我的回复类似于

 [ { time: '03:45:55',
   absolute_time: '2019-07-17T03:45:55Z',
   log:
    '/home/ec2-user/soapui-report/2019-07-17/154513482/Project Report.pdf',
   level: 'NORMAL',
   user: 'ec2-user',
   stepctx: '1',
   node: 'QA-Server-jmeter' },
 { time: '03:45:55',
   absolute_time: '2019-07-17T03:45:55Z',
   log:
    'Login:https://training-labs.com/\nUsername : michelle@test.com.test ',
   level: 'NORMAL',
   user: 'ec2-user',
   stepctx: '1',
   node: 'QA-Server-jmeter' },
 { time: '03:45:55',
   absolute_time: '2019-07-17T03:45:55Z',
   log: '221 2.0.0 Bye',
   level: 'ERROR',
   user: 'ec2-user',
   stepctx: '1',
   node: 'QA-Server-jmeter' } ]

我想从 JSON 响应中获取 'Username' 的值。即'michelle@test.com.test'。我正在使用打字稿。非常感谢帮助。谢谢

如果您希望 用户名 仅出现在日志属性中,一种可能的解决方案如下所示。这会创建一个 string array 包含您在回复中找到的所有用户名。

const label = 'Username :';
const usernames = response
    .map(r => r.log)
    .filter(log => log.includes(label))
    .map(log => log.split(label).splice(-1)[0])
    .map(user => user.trim());

将其设为字符串 return 匹配的所有内容:

JSON.stringify(response)
.match(/(?<=Username : )(.*@.*)(?= )/)

正则表达式可以改进,但我认为你明白了。