Why are my objects displayed as an “object object”?

I am trying to break down an array of records by age, but all I get is:

[object Object], [object Object], [object Object]

How can I make it display record values?

students = [ {name: "timothy", age: "9"}, {name: "claire", age: "12"}, {name: "michael", age: "20"} ]; for (var i = 0; i < students.length; i++) { for (var j = i + 1; j < students.length; j++) { if (Number(students[i].age) > Number(students[j].age)) { tempValue = students[j].age; students[j].age = students[i].age; students[i].age = tempValue; } } } alert(students); 
+4
source share
2 answers

By default, all objects in JavaScript turn into "[object Object]" when they are converted to a string (as is the case with alert() ).

You can try:

  • Use console.log or a debugger to check the array (instead of using alert ())

     console.log(students); //Open your browser developer tools to see the console. //Try F12, ctrl+shift+J or ctrl+shift+I as shortcuts 
  • Use the JSON.stringify function to serialize objects.

     JSON.stringify({a:1}); //yields '{"a":1}' 
  • Give your objects your own toString method

     var x = { a : 17, toString: function(){ return 'I have a ' + this.a; } }; alert(x); //gives "I have a 17" 
+10
source

In supported browsers, you can warn or write a JSON string representation:

 alert(JSON.stringify(students)); 
+1
source

Source: https://habr.com/ru/post/1379793/


All Articles