5

I tried to pull some data from a json file and so I used console.log() to test it. To make sure it's easier to read, I used template literals to highlight it with some extra information. However, I keep getting [object, Object]. I assumed that I failed to pull the data and inspected the json file data for hours. Eventually, I found out I require the data correctly but it was console.log() failed me.

So I thought it's a template literals thing, so I tried the other two ways and they still got the same results. Why?

var obj = {
    "date": "Sun Jun 14 21:36:17 UTC 2009",
    "user": "captain_pete",
    "tweet": "Reading the tweets coming out of Iran... The whole thing is terrifying and incredibly sad..."
}

console.log(obj)
console.log('Obj1: ' + obj)
console.log('Obj2: ' + obj.toString()
console.log(`Obj3: ${obj}`)

Output:

{date: 'Sun Jun 14 21:36:17 UTC 2009', user: 'captain_pete', tweet:'Reading the tweets coming out of Iran... The whole thing is terrifying and incredibly sad...'} 
Obj1: [object Object]
Obj2: [object Object] 
Obj3: [object Object]
2
  • You are trying to convert it to a string by using it in a template literal or string concatenation, which just gives you what you are seeing. If you want to log the object and navigate through its properties log it directly, eg console.log('some text', obj) note obj is being passed as a different argument Commented Oct 7, 2021 at 1:47
  • If you want print a single property in an object, console.log('Obj1: ' + obj.date) or console.log('Obj1: ' + obj["date"]) Commented Oct 7, 2021 at 1:47

1 Answer 1

2

The last three lines are all invoking Object.toString() on obj, which by default returns a string in the form of [object type].

If you want the object as a string, you can use JSON.stringify:

var obj = {
    "date": "Sun Jun 14 21:36:17 UTC 2009",
    "user": "captain_pete",
    "tweet": "Reading the tweets coming out of Iran... The whole thing is terrifying and incredibly sad..."
}

Object.prototype.toString = function(){
  return JSON.stringify(this)
}

console.log(obj)
console.log('Obj1: ' + obj)
console.log('Obj2: ' + obj.toString())
console.log(`Obj3: ${obj}`)

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

2 Comments

Is this the same as type conversion like number + string ends up as string?
@MeoW Yes, it is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.