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);
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);
Share
Improve this question
edited Nov 5, 2011 at 19:18
hugomg
70k29 gold badges164 silver badges255 bronze badges
asked Nov 5, 2011 at 18:26
jasonscottjasonscott
871 gold badge2 silver badges4 bronze badges
2
- 3 possible duplicate of How can i print a javascript object? – Felix Kling Commented Nov 5, 2011 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 Commented Nov 5, 2011 at 18:42
2 Answers
Reset to default 11By 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"
In supported browsers you could alert or log a JSON string representation:
alert(JSON.stringify(students));