Why does [{"value":"tag1"} turns into [object Object] when logged?

Viewed 585

On my node.js server I have the following code:

var tags = [{"value":"tag1"},{"value":"tag2"}];
console.log("tags: " + tags);

I expected the console to say this:

tags: [{"value":"tag1"},{"value":"tag2"}]

But instead got this:

tags: [object Object],[object Object]

Why does this happen? It's causing problems in my code because I'm trying to access the values but can't.

6 Answers

When you do "tags: " + tags, the toString method of objects is called in order to do the operation.

Change

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

into

console.log("tags: ", tags);

so that the console.log function of node can do its own more interesting conversion.

You have two options:

1: Use the comma , instead of concatenating the strings together, to avoid toString() being called and creating [object Object]:

var tags = [{"value": "tag1"}, {"value": "tag2"}];
console.log("Tags: ", tags);

2: Use JSON.stringify() on the object to convert it into a string which can be read:

var tags = [{"value": "tag1"}, {"value": "tag2"}];
console.log("Tags: ", JSON.stringify(tags));

You can also use JSON to log Objects properly if you want to concatenate the strings.

var tags = [{
  "value": "tag1"
}, {
  "value": "tag2"
}];
console.log("tags: " + JSON.stringify(tags))

Why does this happen?

It happens because when you try to concatenate any variable with a string using + operator, javascript converts the value of the variable to a string.

When you create a concatenated string using the + operator, the .toString() method is called on the non-string parts to convert them to readable strings – and this method returns [object Object] for plain objects.

If you want to see the actual content of the array, use :

  • console.log("tags: ", tags); (when used in the browser's console, allows for an "interactive" log : you'll be able to click on the array and unfold its content) ;
  • or console.log("tags: " + JSON.stringify(tags)); if you just want to see the content of the array printed (use JSON.stringify(tags, null, 2) for pretty print with 2-spaces indent).

'+' stringifies the object, thus results [object Object], You need to use JSON.stringify() to convert your object to a JSON string before using console with '+', otherwise use console with ",".

Related