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;
}
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 = [];
?
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.
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).
var array = []
for( var prop in testObj )
{
array.push( testObj[prop] );
}
Is this what you want?
精彩评论