5

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);
hugomg
  • 68,213
  • 24
  • 160
  • 246
jasonscott
  • 87
  • 1
  • 2
  • 4
  • 3
    possible duplicate of [How can i print a javascript object?](http://stackoverflow.com/questions/957537/how-can-i-print-a-javascript-object) – Felix Kling Nov 05 '11 at 18:33
  • 1
    btw, be careful about using undeclared variables like "students" and "tempValue". By default they can be global and that is often not what you want. – hugomg Nov 05 '11 at 18:42

2 Answers2

11

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"
    
hugomg
  • 68,213
  • 24
  • 160
  • 246
2

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

alert(JSON.stringify(students));
Ryan Lynch
  • 7,676
  • 1
  • 24
  • 33