4

If I have any object, maybe new MyObject(), and I wnat show all inner properties. How can I do it?

When use alert(new MyObject()) the result is [object Object]. But I want all inner properties. For example...

var MyObject = function() {
    this.prop1 = "Hello World";
    this.prop2 = "LOL";
    this.recursive = this;
    this.func = function() { return "func return"; }
}
alert(new MyObject());

In this case how can I do to show { prop1 = "Hello World", prop2 = "LOL", etc... }

Sergio Cabral
  • 6,490
  • 2
  • 35
  • 37

5 Answers5

3

You can write this function and convert any object to string.

Look JSFiddle

////For NodeJS remove comment below:
//var window = { };

function ToString(obj) {
    clearTimeout(window.ToStringTimeout);

    var result;
    var ident = arguments.length >= 2 ? arguments[1] : undefined;

    if (obj == null) {
        result = String(obj);
    }

    var objString;
    try {
        objString = obj.toString();
    } catch (err1) {
        try {
            objString = String(obj); 
        } catch (err2) {
            try {
                objString = obj + "";
            } catch (err3) {
                objString = "ERROR CONVERT STRING";
            }
        }
    }

    if (!result) {
        window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
        if (window.ToStringRecursive.indexOf(obj) >= 0) {
            result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : objString) : obj;
        } else {
            window.ToStringRecursive.push(obj);
        }
        if (!result) {
            switch (typeof obj) {
                case "string":
                    result = '"' + obj + '"';
                    break;
                case "function":
                    result = obj.name || objString;
                    break;
                case "object":
                    var indent = Array(ident || 1).join('\t'),
                        isArray = Array.isArray(obj);
                    result = '{[' [+isArray] + Object.keys(obj).map(
                        function(key) {
                            return '\n\t' + indent + key + ': ' + ToString(obj[key], (ident || 1) + 1);
                        }).join(',') + '\n' + indent + '}]' [+isArray];
                    break;
                default:
                    result = objString;
                    break;
            }
        }
    }

    window.ToStringTimeout = setTimeout(function() {
        delete window.ToStringTimeout;
        delete window.ToStringRecursive;
    }, 100);

    return result;
}

And use this:

console.log(ToString(new MyObject()));

To show this:

{
    prop1: "Hello World",
    prop2: "LOL",
    recursive: [object Object],
    func: function () { return "func return"; }
}

Observe... when any property is recursive this not show again, because this is infinite.

Sergio Cabral
  • 6,490
  • 2
  • 35
  • 37
2

Use This :

 var MyObject = function() {
     this.prop1 = "Hello World";
     this.prop2 = "LOL";
     this.recursive = this;
     this.func = function() { return "func return"; } }

 console.log(eval(new MyObject()));

Result is :

{ prop1: 'Hello World',
  prop2: 'LOL',
  recursive: [Circular],
  func: [Function] }
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
Meena
  • 97
  • 2
0

Like this:

var obj = {type:"Fiat", model:"500", color:"white"};
var str = '';
    
for (var p in obj) {
  str = str + p + " = " + obj[p] + ',';
}
console.log(str);
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
0

var MyObject = function() {
  this.prop1 = "Hello World";
  this.prop2 = "LOL";
  this.recursive = this;
  this.func = function() {
    return this.recursive.prop1 + "," + this.recursive.prop2;
  }
}
var output = new MyObject();
alert(output.func());
Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
0

Much more efficient... using JSON.stringify with a replacer to evict recursive property:

function toString(instance, space = '  ') {
  const objects = [];
  const replacer = (key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (objects.findIndex(object => object === value) >= 0) {
        return ({}).toString();
      }
      objects.push(value);
    }
    return value;
  };
  return JSON.stringify(instance, replacer, space);
}
Sergio Cabral
  • 6,490
  • 2
  • 35
  • 37