javascript - 从多个对象中获取特定的键和值

标签 javascript arrays unit-testing object webdriver-io

状态:

// 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/

相关文章:

javascript - Angular.js 仅在前端或后端处理数据

javascript - 如何在成功回调后使用 jquery

javascript - 如何使用reduce按json分组?

php - 在 Laravel 中仅返回值(无键/关联数组)

javascript - UnderscoreJS : Getting only top 5 using the _. 每个方法

Angular 2测试: calling function directly cannot change the component object itself

unit-testing - 无法让 NUnit 的 Assert.Throws 正常工作

javascript - 一般脚本 : selecting the input element for which keypress event is fired, 没有实际传递 ID 等

ruby-on-rails - Controller 测试使用 Rspec 显示页面,它给出错误 nil & 并渲染空页面

javascript - 在对象内创建对象 Javascript