状态:
// WebdriverIO log function
browser.log('browser').then(function(logs) {
console.log(logs.value);
});
返回以下数组:
[ { level: 'INFO',
message: 'https://localhost:3000/ 42:14 "foo"',
timestamp: 1485857149752 },
{ level: 'INFO',
message: 'https://localhost:3000/ 43:14 "bar"',
timestamp: 1485857149752 },
{ level: 'INFO',
message: 'https://localhost:3000/ 46:14 Array[6]',
timestamp: 1485857149755 },
{ level: 'SEVERE',
message: 'https://localhost:3000/favicon.ico - Failed to load resource: the server responded with a status of 404 (Not Found)',
timestamp: 1485857149834 } ]
目标:
我想创建一个稍后可以使用的方法,该方法返回日志条目列表。在我的示例应用程序中就是这样:
foo
bar
我不知道如何仅循环获取“message”键及其值。
要过滤以便仅获取“foo”或“bar”,我将使用 RegEx 或 .split 函数。
最佳答案
您可以使用 Array.prototype.reduce()
来做到这一点:
let arr = [{
level: 'INFO',
message: 'https://localhost:3000/ 42:14 "foo"',
timestamp: 1485857149752
}, {
level: 'INFO',
message: 'https://localhost:3000/ 43:14 "bar"',
timestamp: 1485857149752
}, {
level: 'INFO',
message: 'https://localhost:3000/ 46:14 Array[6]',
timestamp: 1485857149755
}, {
level: 'SEVERE',
message: 'https://localhost:3000/favicon.ico - Failed to load resource: the server responded with a status of 404 (Not Found)',
timestamp: 1485857149834
}];
let res = arr.reduce((a, b) => {
if (b.level === 'INFO') {
a.push(b.message.split(" ").pop().replace(/"/g, ""));
}
return a;
}, []);
console.log(res);
记住在链接所有之前执行检查
b.message.split(" ").pop().replace(/"/g, "")
避免出现空指针异常。
旁注:
OP 没有指定,但如果您要收集的消息也包含空格,您可以替换上面的拆分并使用 @JLRishe's regex instead
关于javascript - 从多个对象中获取特定的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41955011/