Skip to main content
  1. About
  2. For Teams
Asked
Viewed 518 times
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... }

8
  • 2
    JSON.stringify(object) ... ?
    Damon
    –  Damon
    2016-08-03 03:46:07 +00:00
    Commented Aug 3, 2016 at 3:46
  • 1
    @Damon It's a circular reference.
    Spencer Wieczorek
    –  Spencer Wieczorek
    2016-08-03 03:46:58 +00:00
    Commented Aug 3, 2016 at 3:46
  • 1
    Normally you use JSON.stringify(new MyObject()). Just note it will not work because of the circular referencing this.recursive = this, because it would print forever. To remedy that you can use the second paramater, see this answer.
    Spencer Wieczorek
    –  Spencer Wieczorek
    2016-08-03 03:49:20 +00:00
    Commented Aug 3, 2016 at 3:49
  • @Spencer just noticed :) still I believe stringify accepts a callback to handle this if necessary.
    Damon
    –  Damon
    2016-08-03 03:50:37 +00:00
    Commented Aug 3, 2016 at 3:50
  • 1
    @SergioCabral Read the comments above. I already explained that exactly, and gave a link to the solution.
    Spencer Wieczorek
    –  Spencer Wieczorek
    2016-08-03 03:59:11 +00:00
    Commented Aug 3, 2016 at 3:59

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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] }

1 Comment

Is not string, ok?
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);

4 Comments

That's not what the OP is wanting.
umm, true. how about that?
fixed it. ...ambien.
i see. it runs fine for me. jsfiddle.net/rhroyston/v71y0emo/1
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());

2 Comments

Yes he want to get object value.Hence i create instance and call function for get value.
No they want to print it as an object literal.
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);
}

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.