Convert object notation to array

I used the literal as a dictionary, but a third-party binding tool only accepts arrays.

This is one way, is there a better one?

var arr = []; $.each(objectLiteral, function () { arr.push(this); }); 
+7
source share
3 answers

I think there is nothing wrong with your decision.

This is a shorter option:

 var arr = $.map(objectLiteral, function (value) { return value; }); 
+9
source

Your method is accurate, understandable, and readable. To do this without jQuery, use the for (..in..) syntax:

 var arr = []; for (prop in objectLiteral) { arr.push(objectLiteral[prop]); } 
+7
source

In vanilla js ...

If we want to convert an object literal

 var obj = { species: 'canine', name: 'Charlie', age: 4 } 

into an array of arrays

 [['species', 'canine'], ['name', 'Charlie'], ['age', 4]] 

here is one way

 function objToArr(obj){ var arr = []; for (var key in obj){ arr.push([key, obj[key]]); } return arr; } 
+2
source

All Articles