1

I have an object in typescript "obj". When I run:

console.log(obj);

It renders as the following in the terminal console:

[object Object]

It's only after i wrap it in a JSON.stringify(obj) method that it renders the object as expected:

[{"allowed_values":["true"],"property":"pro1","required":"true"}]

What am I missing? Why is the object not being rendered as a JSON when I run "console.log()"?


Here is the scenario that captures the issue I am seeing:

violation = {"my_properties":[{"allowed_values":[{"Ref":"The bucket's logical resource name"}],"property":"BucketPolicy.Properties.Bucket","required":"true"}],"decision":"deny","message":"Some message.","policy_id":"FT_S3_0004","resource":"MyFirstBucketB8884501","type":"AWS::S3::Bucket","controls":["NIST-800-53-SA-8(2)"]}
console.log(violation)

This outputs:

{
  my_properties: [
    {
      allowed_values: [Array],
      property: 'BucketPolicy.Properties.Bucket',
      required: 'true'
    }
  ],
  decision: 'deny',
  message: 'Some message.',
  policy_id: 'FT_S3_0004',
  resource: 'MyFirstBucketB8884501',
  type: 'AWS::S3::Bucket',
  controls: [ 'NIST-800-53-SA-8(2)' ]
}

(notice that it prints [Array] rather than the actual elements in the array).

7
  • JSON !== Object Commented Jul 22, 2021 at 23:21
  • what does console.log(typeof obj); show? Commented Jul 22, 2021 at 23:23
  • @NickParsons object Commented Jul 22, 2021 at 23:27
  • @Darth.Vader Make sure you're not concatenating a string with your obj. Also, if you import util using const util = require("util"); what does console.log(obj[util.inspect.custom]) show? Commented Jul 22, 2021 at 23:37
  • The code you've posted doesn't do what you claim it does. Post a complete minimal example that demonstrates the problem and then we can help you find exactly what's wrong. Commented Jul 22, 2021 at 23:44

2 Answers 2

2

I think you aren't telling us the whole story. I can log the array object just fine using

console.log([{"allowed_values":["true"],"property":"pro1","required":"true"}]);

What you are seeing will happen, however, if you do something like this:

console.log("obj:" + obj);

In that case, .toString() is implicitly called in order to append the object to the preceding string. You can do this alternative and it will work:

console.log("obj:", obj);
Sign up to request clarification or add additional context in comments.

Comments

0

You can't convert an entire object to a string, and [object Object] is what the console.log outputs when it sees an object. Only if we convert it to a string then the logger will long the string representation of the object.

1 Comment

The console logs that actual object when it sees an object, not [object Object] -console.log({x: 1}); shows {x: 1}, and not [object Object]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.