Javascript Data Structure Tutorial - Javascript Array of Objects








Arrays can consist of objects, and all the functions and properties of arrays work with objects.

Example


function Point(x,y) { // w ww .  j  a  v  a 2 s  .  c  o  m
    this.x = x; 
    this.y = y; 
} 

function displayPoint(arr) { 
    for (var i = 0; i < arr.length; ++i) { 
        console.log(arr[i].x + ", " + arr[i].y); 
    } 
} 
var p1 = new Point(1,2); 
var p2 = new Point(3,5); 
var p3 = new Point(2,8); 
var p4 = new Point(4,4); 
var points = [p1,p2,p3,p4]; 
for (var i = 0; i < points.length; ++i) { 
    console.log("Point " + parseInt(i+1) + ": " + points[i].x + ", " + points[i].y); 
} 

var p5 = new Point(12,-3); 
points.push(p5); 
console.log("After push: "); 
displayPoint(points); 
points.shift(); 
console.log("After shift: "); 
displayPoint(points); 

The code above generates the following result.

Point 1: 1, 2
Point 2: 3, 5
Point 3: 2, 8
Point 4: 4, 4
After push:
1, 2
3, 5
2, 8
4, 4
12, -3
After shift:
3, 5
2, 8
4, 4
12, -3




Arrays in Objects

In the following example, we create an object that stores the values.

Here is the code:


function MyData() { //from  w w w  . j  a va2s  .  c o  m
    this.dataStore = []; 
    this.add = add; 
    this.average = average; 
} 

function add(temp) { 
    this.dataStore.push(temp); 
} 
function average() { 
    var total = 0; 
    for (var i = 0; i < this.dataStore.length; ++i) { 
        total += this.dataStore[i]; 
    } 
    return total / this.dataStore.length; 
} 


var myData = new MyData(); 
myData.add(2); 
myData.add(5); 
myData.add(1); 
myData.add(5); 
myData.add(5); 
myData.add(0); 
myData.add(2); 
myData.add(9); 
console.log(myData.average()); 

The code above generates the following result.