priyank
priyank

Reputation: 4724

How do I convert this object to an array in JavaScript?

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;
}

Upvotes: 0

Views: 271

Answers (4)

Stefan Kendall
Stefan Kendall

Reputation: 67822

var array = []
for( var prop in testObj )
{
    array.push( testObj[prop] );
}

Is this what you want?

Upvotes: 0

Gabriel McAdams
Gabriel McAdams

Reputation: 58261

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).

Upvotes: 0

Justin Swartsel
Justin Swartsel

Reputation: 3431

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 = [];?

Upvotes: 1

KP.
KP.

Reputation: 13730

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.

Upvotes: 0

Related Questions