+ 1
Why are my users being logged as [object Object] when logging my array/user instead of giving me the values [name, age]?
9943 Respuestas
+ 5
You code looks really clean and neat. SoloLearn console doesnt work as good as real browser console.
I tried ur code in separate files in Firefox and Chrome and they can log the info as intended.
+ 8
In Sololearn Playground web, you have to convert the array or object data to string, so that you can view the data in string format.
Try this
console.log(JSON.stringify(users, null, 2));
+ 4
Coding Noob use JSON.stringify
console.log(JSON.stringify(users));
+ 4
toString() will not work here. you get the same [object Object] output.
your class must have to have a toString() method to be able to return a custom string representation of your object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
in your code, you can add this inside your class definition
toString(){
return `${this._name}, ${this._age} `;
}
then you can use console.log(users.toString())
to get a custom string representation of your objects.
+ 2
Thank you! I wrote it out on my phone in sololearn since I'm not at my computer at the moment and had a feeling it was the sololearn console. I appreciate you verifying this for me.
+ 2
Bob_Li I haven't learned anything backend related which is what JSON.stringify appears to be for. I just read up on it and learned some new stuff, so thank you.
+ 2
Coding Noob JSON.stringify have formatting options for prettier display...
try Calviղ's suggestion. It is prettier.
you learn fast.😁
+ 2
Bob_Li I tried it out and I like it. Thank you, I have been studying for about 2 months now.
+ 1
Example when i log newUser it returns [object Object] instead of ['Paolo', 34].
If I log newUser.name it logs 'Paolo'
+ 1
it's not backend, and it's actually an often used function. Very useful to know.😊
+ 1
Bob_Li how does it differ from using toString()? I'm reading about both and they seem to be the same?
+ 1
Attempting to concatenate an object with a string typically results in the string "[object Object]" being returned. The console will display a picture of the item when you log an array or user in JavaScript. The object will be shown in the console as "[object Object]" if it is not a primitive data type (such as a string, integer, boolean, etc.).
You must access the object's properties and report each one separately if you want to log your array's or user's values rather than the object representation. You may log users in the following way, for instance, if you have an array of users with the "name" and "age" properties:
const users = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 }
];
users.forEach(user => {
console.log(user.name, user.age);
});