如何打印出对象的所有键和子键

时间:2018-11-16 13:48:08

标签: javascript

间距为http://jsfiddle.net/eopth925/1/的JSFiddle版本

var obj = {
	test: {
  	test2: "test",
    test3: {
    	base: {
      	base: {
        	check: function() {
          	return this;
          },
          va: function() {
          	return "value";
          },
          do: "this is dummy"
        }
      }
    },
    test4: {
    	test5: function() {
      	var k = 2;
        k++;
        
        return k;
      },
      test6: {
      	test7: {
        	test8: "test8",
          test9: {
          	test10: "test10",
            test11: function() {
            	return window.jQuery;
            },
            test12: "test12",
            test13: function() {
            	return window.ga;
            }
          }
        }
      }
    }
  },
  
};

var output = "";
var addbreak = "\n";

var RunFunc = {
  propertypri: function(a) {
    Object.keys(a).forEach(function(e) {
      if (typeof a[e] === 'object') {
        output += `Main Key=${e}`;
        RunFunc.propertyobj(e, a[e]);
      }
      else {
        output += `Main Key=${e} value=${a[e]}` + addbreak;
      }
    });
    console.log(output);
  },
  propertyobj: function(key, keyObj) {
    Object.keys(keyObj).forEach(function(e) {
      if (typeof keyObj[e] === 'object') {
        output += ` Subkey=${e}`;
        RunFunc.propertyobj(e, keyObj[e]);
      }
      else {
        output += ` Subkey=${e} value=${keyObj[e]}` + addbreak;
      }
    });
  }
};

RunFunc.propertypri(obj);

其输出方式不友好。我想在输出中添加适当的缩进。我确信,有一种更有效的方式来完成我要完成的任务。

如何更新脚本,使其显示如下:

Main Key=test
  Subkey=test2 value=test
  Subkey=test3
    Subkey=base
      Subkey=base
        Subkey=check value=function() {
            return this;
          }
        Subkey=va value=function() {
            return "value";
          }
        Subkey=do value=this is dummy
  Subkey=test4
    Subkey=test5 value=function() {
        var k = 2;
        k++;

        return k;
      }
    Subkey=test6
      Subkey=test7
        Subkey=test8 value=test8
        Subkey=test9
          Subkey=test10 value=test10
          Subkey=test11 value=function() {
                return window.jQuery;
            }
            ...

2 个答案:

答案 0 :(得分:-1)

为什么不只使用JSON.stringify

console.log(JSON.stringify(foo,(key,val)=>(typeof val ==='function'?''+ val:val),2))

答案 1 :(得分:-2)

const yourObject = {/ *此处的对象属性* /}

function printKeys(obj) {
  if (typeof obj === 'object') {
    const keys = Object.keys(obj)
    for (const key of keys) {
      printKeys(key)
    }
  } else {
    console.log(obj)
  }
}