Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my objects showing up as "[object Object]"?

Tags:

javascript

I'm trying to bubble sort an array of records by age but all I get is:

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

How can I get it to display the values of the record?

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);
like image 860
jasonscott Avatar asked Nov 05 '11 18:11

jasonscott


2 Answers

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

You can try to:

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

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

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

    var x = {
        a : 17,
        toString: function(){
            return 'I have a ' + this.a;
        }
    };
    alert(x); //gives "I have a 17"
    
like image 144
hugomg Avatar answered Nov 11 '22 22:11

hugomg


In supported browsers you could alert or log a JSON string representation:

alert(JSON.stringify(students));
like image 23
Ryan Lynch Avatar answered Nov 11 '22 22:11

Ryan Lynch