views:

90

answers:

4

How do I convert testObj to an array?

function MinEvent(event, width, left){
  this.start = event.start;
  this.end = event.end;
  this.width = width;
  this.top = event.start;
  this.left = left;
}

var testObj = {};
for (var j=0; j<eventLists.length; j++) {
  var eve = eventLists[j];
  var event = new MinEvent(eventList[j], width, left);
  testObj[eve.id] = event;
}
A: 

I'm not sure why you'd want to do that. JavaScript objects are actually the same as an associative array already. You could access all of its properties and methods like this:

for(prop in obj) {
    alert(prop + ” value : ”+ obj[prop];
}

Maybe it would help if you told us what you wanted to do once you converted the object inot an array (and what you want the result to look like).

Gabriel McAdams
A: 

If you declare testObj as an array initially you don't need to convert it.

//declare the array
var testObj = new Array();

or

//declare the array
var testObj = [];

Index based access should work for either of these. I.e.

testObj[0] = "someval";

etc.

KP
LOL why people downed every answer to this question is beyond me. They're all valid, including mine. It's a simple javascript array. It's like grade school around here. Oh me! me! me! I had my hand up first ;)
KP
A: 

Technically every object in javascript can be treated like an array. Your code should work as-is.

But either way, looking at your code, why not define testObj as var testObj = [];?

Justin Swartsel
Ya I got it. I wonder why didn't I think about this? Thanks
priyank
A: 
var array = []
for( var prop in testObj )
{
array.push( testObj[prop] );
}

Is this what you want?

Stefan Kendall