简体   繁体   中英

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

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

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

testObj[0] = "someval";

etc.

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

Is this what you want?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM