0

Is it possible to make a JavaScript object become an array? That is, while keeping its existing attributes, start behaving like an array with regard to length, push, forEach etc? I had the vague idea that this might be possible by reassigning the prototype but some attempts to do this by trial and error haven't yielded any results.

rwallace
  • 31,405
  • 40
  • 123
  • 242

2 Answers2

1

No, you cannot. While you could theoretically (through non-standard ways) reassign the prototype, it will not change its internal [[Class]] and get a magic .length property.

Instead, try to copy all the properties of the object onto a new array.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

I'm not sure why you'd want to do this, other than for access to .length, .push(), and forEach, as you mentioned. As far as I know, you cannot force these properties/functions to work on an object, but you can certainly get around them:

.length (from here):

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myObj);

.push():

obj.key = value; //there isn't a much shorter way to add something to an object since you have to specify a key and a value

forEach:

for(key in obj){
  var value;
  if(obj.hasOwnProperty(key)){
     value = obj[key]; //you now have access to the key and the value in each iteration of obj
  }
}
Community
  • 1
  • 1
AstroCB
  • 12,337
  • 20
  • 57
  • 73