有没有办法在Chrome DevTools中搜索控制台记录的对象以获取特定值?

问题描述 投票:21回答:1

我想console.log()一个对象,并在该对象中搜索特定的值。这可能吗?

注意:我正在尝试搜索的对象是庞大且多维的,因此扩展每个字段并执行简单的Ctrl + F查找并不理想。

google-chrome google-chrome-devtools
1个回答
22
投票

下面的代码添加了类似于您正在寻找的控制台对象的内容

console.logSearchingForValue

广度优先搜索,匹配等效的“JSON”值,正确处理NaN,返回多个位置,并使未引用的数字索引表达式留给读者练习。 :)

交换不同的平等定义已经非常容易了。

var searchHaystack = function(haystack, needle, path, equalityFn, visited) {

  if(typeof haystack != "object") {
    console.warn("non-object haystack at " + path.join("."));
  }

  if(visited.has(haystack))
    return [false, null];

  for(var key in haystack) {
    if(!haystack.hasOwnProperty(key))
      continue;

    if(equalityFn(needle, haystack[key])) {
      path.push(key);
      return [true, path];
    }

    visited.add(haystack);
    if(typeof haystack[key] == "object") {
      var pCopy = path.slice();
      pCopy.push(key);
      var deeper = searchHaystack(haystack[key], needle, pCopy, equalityFn, visited);
      if(deeper[0]) {
        return deeper;
      }
    }
  }
  return [false, null];
}

var pathToIndexExpression = function(path) {
   var prefix = path[0];
   path = path.slice(1);
   for(var i = 0; i < path.length; i++) {
      if(typeof path[i] == "string")
         path[i] = "\"" + path[i] + "\"";
   }
   return prefix + "[" + path.join("][") + "]"
}

console.logSearchingForValue = function(haystack, needle) {
   this.log("Searching");
   this.log(haystack);
   this.log("for");
   this.log(needle);
   var visited = new Set();
   var strictEquals = function(a,b) { return a === b; };
   var result = searchHaystack(haystack, needle, ["<haystack>"], strictEquals, visited);
   if(result[0]) {
      this.log("Found it!");
      this.log(pathToIndexExpression(result[1]));
   }
   else {
      this.log("didn't find it");
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.