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 NULL
s 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 []
... setting votes[7777]
is going to reindex the array to accommodate 7,778 elements... with lots and lots of undefined elements (which JSON.stringify()
will convert to null
).
Plus, you're setting named properties on an array:
votes[movieID]=[];
votes[movieID].stay = stay;
Here's a functional sample using objects (fiddle):
var votes = {
// Movie #1
'55555': {
stay: 'yes',
scenes: 1,
outtakes: 0,
enhanced: 0,
teaser: 0
},
// Movie #2
'77777': {
stay: 'no',
scenes: 0,
outtakes: 0,
enhanced: 0,
teaser: 0
}
};
console.log(votes[77777].stay);
console.log(votes);
and a 1-to-1 change in your provided code (fiddle):
//Movie #1
var movieID = 55555;
var stay = 'yes';
var votes = {}; // changed to {}
votes[movieID]= {}; // changed to {}
votes[movieID].stay = stay;
var scenes = 1;
votes[movieID].scenes = scenes;
var outtakes = 0;
votes[movieID].outtakes = outtakes;
var enhanced = 0;
votes[movieID].enhanced = enhanced;
var teaser = 0;
votes[movieID].teaser = teaser;
//Movie #2
var movieID = 77777;
var stay = 'no';
//var votes = []; removed
votes[movieID]= {}; // changed to {}
votes[movieID].stay = stay;
var scenes = 0;
votes[movieID].scenes = scenes;
var outtakes = 0;
votes[movieID].outtakes = outtakes;
var enhanced = 0;
votes[movieID].enhanced = enhanced;
var teaser = 0;
votes[movieID].teaser = teaser;
//Alert Single Item from votes
alert(votes['77777'].stay);
//Alert entire object/array
alert(JSON.stringify(votes));//returns NULLs