Pretty-printing of objects - Node.js Object

Node.js examples for Object:Object Operation

Description

Pretty-printing of objects

Demo Code



// Pretty-printing of objects
var pp = function(obj, depth) {
  if (depth == undefined) depth = 4;
  depth -= 1;//  ww w. ja  v  a2s.  c o m
  if (depth <= 0)
    return '' + obj;
  if (obj instanceof Array) {
    var str = "[";
    obj.forEach(function(i){
      str += pp(i,depth) + ", ";
    });
    return str + "]";
  }
  if (obj instanceof String)
    return '"'+str+'"';
  if (obj instanceof Object){
    var str="{"; //variable which will hold property values
    for(prop in obj){
      if (prop == "ancestor")
        depth = 0;
      str+= pp(prop,depth) + ":" + pp(obj[prop],depth) +", ";
    }
    return str + "}";
  }
  return '' + obj;
}

Related Tutorials