My entire code example is below and on jsFiddle: http://jsfiddle.net/rEhvt/.
I’m trying to alert() my multi-dimensional JavaScript object. If I alert() a single property of the object – it works. For example:
alert(votes['77777'].stay);
However, if I try to alert() the entire object, then I either get a lot of NULLs or blanks. I tried the following:
alert(JSON.stringify(votes));//returns lots of NULLs
alert(votes.join('\n'));//returns lots of blanks
My intention is to eventually send the object to localStorage with
localStorage['votes']=JSON.stringify(votes);
and retrieve it with
retrievedVotes=JSON.parse(localStorage['votes'])
However, I want to first be able to see the object structure. This is my first attempts at understanding multi-dimensional objects with JavaScript, so any help you can offer is greatly appreciated! Below is all of my code, which is also on jsFiddle: http://jsfiddle.net/rEhvt/.
//Movie #1
var movieID = 55555;
var stay = 'yes';
var votes = [];
votes[movieID]=[];
votes[movieID].stay = stay;
var scenes = 1;
votes[movieID].scenes = scenes;
//Movie #2
var movieID = 77777;
var stay = 'no';
var votes = [];
votes[movieID]=[];
votes[movieID].stay = stay;
var scenes = 0;
votes[movieID].scenes = scenes;
//Alert Single Item from votes
alert(votes['77777'].stay);
//Alert entire object
alert(JSON.stringify(votes));//returns NULLs
//Alert entire object
alert(votes.join('\n'));//returns lots of blanks
Use an object
{}rather than an array[]… settingvotes[7777]is going to reindex the array to accommodate 7,778 elements… with lots and lots of undefined elements (whichJSON.stringify()will convert tonull).Plus, you’re setting named properties on an array:
Here’s a functional sample using objects (fiddle):
and a 1-to-1 change in your provided code (fiddle):