有没有办法在Chrome Dev Tools中自动扩展对象?

时间:2012-05-05 18:38:06

标签: google-chrome-devtools

每个单一时间我在控制台中查看一个对象我想要扩展它,所以每次单击箭头来执行此操作都很烦人:)是否有快捷方式或设置完成此操作自动?

14 个答案:

答案 0 :(得分:77)

考虑使用console.table()

console.table output

答案 1 :(得分:45)

展开/折叠节点及其所有子节点,

  

Ctrl + Alt +点击选择<点击箭头图标

(请注意,尽管the dev tools doc列出了Ctrl + Alt + Click,但在Windows上只需要Alt + Click)。

答案 2 :(得分:32)

可能不是最好的答案,但我一直在我的代码中这样做。

<强>更新

使用JSON.stringify自动展开您的对象:

> a = [{name: 'Joe', age: 5}, {name: 'John', age: 6}]
> JSON.stringify(a, true, 2)
"[
  {
    "name": "Joe",
    "age": 5
  },
  {
    "name": "John",
    "age": 6
  }
]"

你可以随时创建一个快捷功能,如果它输入所有内容会受到伤害:

j = function(d) {
    return JSON.stringify(d, true, 2)
}

j(a)

上一页回答:

pretty = function(d)
{
  var s = []
  for (var k in d) {
    s.push(k + ': ' + d[k])
  }
  console.log(s.join(', '))
}

然后,而不是:

-> a = [{name: 'Joe', age: 5}, {name: 'John', age: 6}]
-> a
<- [Object, Object]

你这样做:

-> a.forEach(pretty)
<- name: Joe, age: 5
   name: John, age: 6

不是最好的解决方案,但适合我的使用。更深的对象将无法工作,因此可以改进。

答案 3 :(得分:19)

虽然solution提到JSON.stringify对于大多数情况来说非常好,但它有一些限制

  • 它无法处理带有循环引用的项目,因为console.log可以优雅地处理这些对象。
  • 此外,如果你有一棵大树,那么以交互方式折叠一些节点的能力可以使探索变得更容易。

以下是使用underscore.js创造性地(ab)解决上述两个问题的解决方案(使用console.group库):

expandedLog = (function(){
    var MAX_DEPTH = 100;

    return function(item, depth){

        depth = depth || 0;

        if (depth > MAX_DEPTH ) {
            console.log(item);
            return;
        }

        if (_.isObject(item)) {
            _.each(item, function(value, key) {
            console.group(key + ' : ' +(typeof value));
            expandedLog(value, depth + 1);
            console.groupEnd();
            });
        } else {
            console.log(item);
        }
    }
})();

现在正在运行:

expandedLog({
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
})

会给你类似的东西:

output screenshot

可以将MAX_DEPTH的值调整到所需的级别,超出嵌套级别 - 扩展日志将回退到通常的console.log

尝试运行类似:

x = { a: 10, b: 20 }
x.x = x 
expandedLog(x)

enter image description here

请注意,可以轻松删除下划线依赖项 - 只需从the source中提取所需的函数。

另请注意,console.group是非标准的。

答案 4 :(得分:6)

选项+点击Mac。刚刚发现它现在我自己已经完成了我的一周!这和任何事情一样烦人

答案 5 :(得分:6)

这是lorefnon的答案的修改版本,它不依赖于underscorejs:

var expandedLog = (function(MAX_DEPTH){

    return function(item, depth){

        depth    = depth || 0;
        isString = typeof item === 'string'; 
        isDeep   = depth > MAX_DEPTH

        if (isString || isDeep) {
            console.log(item);
            return;
        }

        for(var key in item){
            console.group(key + ' : ' +(typeof item[key]));
            expandedLog(item[key], depth + 1);
            console.groupEnd();
        }
    }
})(100);

答案 6 :(得分:2)

这是我的解决方案,一个迭代对象的所有属性的函数,包括数组。

在这个例子中,我迭代一个简单的多级对象:

    var point = {
            x: 5,
            y: 2,
            innerobj : { innerVal : 1,innerVal2 : 2 },
            $excludedInnerProperties : { test: 1},
            includedInnerProperties : { test: 1}
        };

如果属性以特定后缀开头(即角度对象为$),您也可以排除迭代

&#13;
&#13;
discoverProperties = function (obj, level, excludePrefix) {
        var indent = "----------------------------------------".substring(0, level * 2);
        var str = indent + "level " + level + "\r\n";
        if (typeof (obj) == "undefined")
            return "";
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                var propVal;
                try {
                    propVal = eval('obj.' + property);
                    str += indent + property + "(" + propVal.constructor.name + "):" + propVal + "\r\n";
                    if (typeof (propVal) == 'object' && level < 10 && propVal.constructor.name != "Date" && property.indexOf(excludePrefix) != 0) {
                        if (propVal.hasOwnProperty('length')) {
                            for (var i = 0; i < propVal.length; i++) {
                                if (typeof (propVal) == 'object' && level < 10) {
                                    if (typeof (propVal[i]) != "undefined") {
                                        str += indent + (propVal[i]).constructor.name + "[" + i + "]\r\n";
                                        str += this.discoverProperties(propVal[i], level + 1, excludePrefix);
                                    }
                                }
                                else
                                    str += indent + propVal[i].constructor.name + "[" + i + "]:" + propVal[i] + "\r\n";
                            }
                        }
                        else
                            str += this.discoverProperties(propVal, level + 1, excludePrefix);
                    }
                }
                catch (e) {
                }
            }
        }
        return str;
    };


var point = {
        x: 5,
        y: 2,
        innerobj : { innerVal : 1,innerVal2 : 2 },
        $excludedInnerProperties : { test: 1},
        includedInnerProperties : { test: 1}
    };

document.write("<pre>" + discoverProperties(point,0,'$')+ "</pre>");
&#13;
&#13;
&#13;

这是函数的输出:

level 0
x(Number):5
y(Number):2
innerobj(Object):[object Object]
--level 1
--innerVal(Number):1
--innerVal2(Number):2
$excludedInnerProperties(Object):[object Object]
includedInnerProperties(Object):[object Object]
--level 1
--test(Number):1

您还可以在任何网页中注入此功能并复制和分析所有属性,使用chrome命令在Google页面上尝试:

discoverProperties(google,0,'$')

您也可以使用chrome命令复制命令的输出:

copy(discoverProperties(myvariable,0,'$'))

答案 7 :(得分:1)

它是一个解决方案,但它适用于我。

我在控件/窗口小部件根据用户操作自动更新的情况下使用。例如,当使用twitter的typeahead.js时,一旦您将焦点移出窗口,下拉列表就会消失,建议会从DOM中删除。

在开发工具中右键单击要展开的节点,启用中断... - &gt;子树修改,然后会将您发送到调试器。继续点击 F10 Shift + F11 ,直到你变异为止。一旦变异,那么你可以检查。由于调试器处于活动状态,因此Chrome的用户界面已锁定,并且未关闭下拉列表,建议仍在DOM中。

在对开始插入和不断删除的动态插入节点的布局进行故障排除时非常方便。

答案 8 :(得分:1)

如果您有一个大对象,JSON.stringfy将给出错误Uncaught TypeError:将圆形结构转换为JSON ,这是使用其修改版本的技巧

JSON.stringifyOnce = function(obj, replacer, indent){
    var printedObjects = [];
    var printedObjectKeys = [];

    function printOnceReplacer(key, value){
        if ( printedObjects.length > 2000){ // browsers will not print more than 20K, I don't see the point to allow 2K.. algorithm will not be fast anyway if we have too many objects
        return 'object too long';
        }
        var printedObjIndex = false;
        printedObjects.forEach(function(obj, index){
            if(obj===value){
                printedObjIndex = index;
            }
        });

        if ( key == ''){ //root element
             printedObjects.push(obj);
            printedObjectKeys.push("root");
             return value;
        }

        else if(printedObjIndex+"" != "false" && typeof(value)=="object"){
            if ( printedObjectKeys[printedObjIndex] == "root"){
                return "(pointer to root)";
            }else{
                return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase()  : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")";
            }
        }else{

            var qualifiedKey = key || "(empty key)";
            printedObjects.push(value);
            printedObjectKeys.push(qualifiedKey);
            if(replacer){
                return replacer(key, value);
            }else{
                return value;
            }
        }
    }
    return JSON.stringify(obj, printOnceReplacer, indent);
};

现在您可以使用JSON.stringifyOnce(obj)

答案 9 :(得分:0)

另一种更简单的方法是

  • 使用JSON.stringify(jsonObject)
  • 将结果复制并粘贴到Visual Studio代码中
  • 使用Ctrl + K和Ctrl + F格式化结果
  • 您将看到格式化的扩展对象

我已经尝试过使用简单的对象。

答案 10 :(得分:0)

我真的不喜欢Chrome和Safari如何控制台对象(过度设计)。默认情况下,Console会压缩对象,在扩展对象时对对象键进行排序,并显示原型链中的内部功能。这些功能应为启用设置。默认情况下,开发人员可能会对原始结果感兴趣,因此他们可以检查其代码是否正常工作。这些功能会减慢开发速度,并给出错误的排序结果。

如何在控制台中展开对象

推荐

  1. console.log(JSON.stringify({}, undefined, 2));

    还可以用作功能:

    console.json = object => console.log(JSON.stringify(object, undefined, 2));
    
    console.json({});
    
  2. “ Option + Click”(在Mac上为Chrome)和“ Alt + Click”(在Windows上为Chrome)
    但是,并非所有浏览器(例如Safari)都支持它,并且Console仍会打印原型类型链,展开时对象键会自动排序,等等。

不推荐

我不推荐任何一个最佳答案

  1. console.table()-这仅是浅扩展,不会扩展嵌套对象

  2. 编写一个自定义的underscore.js函数-对于一个简单的解决方案来说,开销太大了

答案 11 :(得分:0)

您可以在这里看到:

https://www.angularjswiki.com/angular/how-to-read-local-json-files-in-angular/

最简单的方法:

import SampleJson from '../../assets/SampleJson.json';
...
console.log(SampleJson);

还必须将以下代码添加到tsconfig:

{  "compilerOptions": {  ..."resolveJsonModule": true, "esModuleInterop": true... } }

我不主张所有权,只是引用了有用的消息来源。

答案 12 :(得分:0)

您可以将 JSON.stringify 打包成一个新函数,例如

jsonLog = function (msg, d) {
  console.log(msg + '\n' + JSON.stringify(d, true, 2))
}

然后

jsonLog('root=', root)

FWIW。 默里

答案 13 :(得分:-1)

您可以通过访问document.getElementsBy来查看您的元素,然后右键单击并复制结果对象。例如:

document.getElementsByTagName('ion-app')返回javascript对象,可以将其复制粘贴到文本编辑器中并完全完成。

更好的是:右键点击结果元素 - '编辑为html' - '全选' - '复制' - '粘贴'