Reputation: 359
i've got this code to list all saved players in a game:
function getAllPlayers(){
for (var i = 0; i <= playerCount; i++){
object[i] = JSON.parse(localStorage.getItem("savedData"+i));
console.log(object[i]);
}
}
I get object[object], which is a collection of objects. In console, I get to see their properties and values, however with:
for (var name in object) {
alert('"' + name + '"="' + object[name] + '"');
}
I still cannot access these properties. Is there a method to get each object into a separate variable, so that I can access them via varName.property syntax?
Upvotes: 0
Views: 1664
Reputation: 1857
The problem is because object
is not really an object this is array of objects and you should access property of some object in this array
for (var i = 0; i < object.length; i++)
for (var name in object[i]) {
alert('"' + name + '"="' + object[i][name] + '"');
}
//currently you have to read it like this
for (var i = 0; i < object.length; i++){
var singleObj = object[i][0]; // additional 0 index
for (var name in singleObj) {
alert('"' + name + '"="' + singleObj[name] + '"');
}
}
like you are using it here
console.log(object[i]);
Upvotes: 1
Reputation: 8715
If your problem is that you are getting [object Object]
in your alert()
box:
alert(someObject)
calls native Object.toString()
method of an argument passed, that is why you are getting [object Object]
.
Use JSON.stringify(someObject)
to simply convert your object to JSON string, or implement your own method to generate a string from an object.
Upvotes: 1