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);
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"
In supported browsers you could alert or log a JSON string representation:
alert(JSON.stringify(students));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With