How To Parse an Array of Objects in Javascript

Javascript gives very easy access to creating Objects, Arrays and variables when compared to every other programming medium. I'll show you the old hack way from the days of IE6 and show you how its gotten easier.

Back in the day you'd declare an array -

var array_of_objects = new Array();

The you could populate it:


The length of the array is found with array_of_objects.length which will return 1.

Using push as I have done updates array_of_objects as an array. Key Value arrays also exist but are not actually arrays. In JS they are Objects.

array_of_objects["key"] = "value";

This is the equivelent of array_of_objects.key

Now lets say you're making a video game and have 1,000 enemies you've created as objects and you need to parse them all. A convienent way to approach this is to store all the data into an array of Sprites. Something like

var Sprites = new Array();


To parse these I'd use this pattern:



Incidentally, if you mix arrays and objects, confusing things happen.

Currently Sprites.length returns 4. Adding object nomenclature does not extend the length. This gets into the precedence of prototype. To give you an example, while Sprites.legth is currently 4 adding this statement:

Sprites.object_key = {"type":"enemy", "health":100};

Sprites.length is still 4. The object aspect of the Sprites object/array is overlooked because it defaults to the Array length function disregarding the values it also has as an object. Virtually everything in JS outside of primitive values is essentially an object but certain functions will default to the most narrow specification available to the datum.

Bracket Terminology makes this more clear. These are equivelent:

	Sprites.object_key = {"type":"enemy", "health":100};
	Sprites["object_key"] = {"type":"enemy", "health":100};

While the second one resembles an array it is actually adding to Sprites an object value. When initialized as an Array, the variable's method calls will default to the methods of the Array global object.


var test = new Array();
	test[1] = "word";

test.length returns 2. As an array it auto-initialized t[0] with an undefined value.

In contrast, as an object there is no length method:
var test_2 = new Object();
	test_2[1] = "word";

test_2.length returns undefined. Arrays and Objects strongly resemble each other but are not identical. In general in JS, everything is an Object but adopts properties of the specific object type it was created to be. This means though that each thing in JS can be extended as an object can.

Anyway back to the question at hand, how to parse an array of objects:

	//this will minus 1 from each sprite's health value

	for(count = 0; count