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.
Asked
Active
Viewed 58 times
0

rwallace
- 31,405
- 40
- 123
- 242
-
A two-dimensional array? – j08691 Jul 01 '14 at 19:20
-
JQuery shows you how [link](http://api.jquery.com/jquery.map/) – Callum Linington Jul 01 '14 at 19:21
-
1That seems like a rather weird thing to do. What do you want it for? You can build an array out of an array-like object pretty simply, but transmuting a non-array-like object into an array? – user2357112 Jul 01 '14 at 19:22
-
Googling "javascript convert object to array" beings up loads of results, the top ones from SO. – j08691 Jul 01 '14 at 19:22
-
1yeah, i think the best bet will be to run the object through jquery's `map` or something, pushing each value into an array – user428517 Jul 01 '14 at 19:22
2 Answers
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
}
}