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

Get specific key and value from multiple objects

状态:

// WebdriverIO log function

browser.log('browser').then(function(logs) {
    console.log(logs.value);
});

returns 我下面的数组:

[ { 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 } ]

目标:

我想创建一个以后可以使用的单一方法,returns 给我一个日志条目列表。在我的示例应用程序中就是这种情况:

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 未指定,但如果您要收集的消息也包含空格,您可以替换上面的拆分并使用

您可以执行以下操作:

var log = [ { 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 } ]

var messages = log
    .filter(function (entry) { return entry.level === 'INFO'; })
    .map(function (entry) { 
        return entry.message.replace(/^([^\s]+\s){2}"?|"$/g, ''); 
    });

console.log(messages)

这不会将 "foo" 转换为 foo 等等,但不清楚您希望代码如何执行此操作(我已经在您的问题)。