Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast javascript object to array. How to?

Tags:

I have made this sandbox test:

<html>     <head>         <title>whatever</title>         <script type="text/javascript">             function myLittleTest() {                 var obj, arr, armap;                  arr = [1, 2, 3, 5, 7, 11];                  obj = {};                 obj = arr;                 alert (typeof arr);                 alert (typeof obj);                  // doesn't work in IE                 armap = obj.map(function (x) { return x * x; });                 alert (typeof armap);              }             myLittleTest();         </script>     </head>     <body>     </body> </html> 

I realize I can use jQuery's function $.map for making that line of code work, but, what am I missing on javascript datatypes?

like image 780
Jhonny D. Cano -Leftware- Avatar asked Oct 05 '10 15:10

Jhonny D. Cano -Leftware-


People also ask

How do you convert an object to an array of objects?

Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) . The Object.

Can we push object into array in JavaScript?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.


1 Answers

If you have an array-like object, (like arguments, for example,) you can get a real array made from it by calling Array.prototype.slice.call(o).

var o = {0:"a", 1:'b', length:2}; var a = Array.prototype.slice.call(o); 

a will be ["a", "b"]. This will only work right if you have a correctly set length property.

like image 109
Sean McMillan Avatar answered Sep 30 '22 18:09

Sean McMillan