Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object literal notation to array

I used a literal as a dictionary, but a third party binding tool only takes arrays.

This is one way, is there a better one?

var arr = [];
$.each(objectLiteral, function () { arr.push(this); });
like image 228
Anders Avatar asked Jan 31 '12 13:01

Anders


People also ask

How do I turn a object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do you convert an object to an array in Python?

Using numpy.asarray() , and true (by default) in the case of np. array() . This means that np. array() will make a copy of the object (by default) and convert that to an array, while np.

How do you convert an object to an array of key:value pairs in typescript?

Object. entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter.


3 Answers

const objectLiteral = { hell: 'devil' };

const ver1 = Object.keys(objectLiteral); // ['hell']
const ver2 = Object.values(objectLiteral); // ['devil']
const ver3 = Object.entries(objectLiteral); // [['hell', 'devil']]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/keys https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/entries

like image 84
basickarl Avatar answered Oct 15 '22 12:10

basickarl


I think there is nothing wrong with your solution.

This is a shorter one:

var arr = $.map(objectLiteral, function (value) { return value; });
like image 9
KARASZI István Avatar answered Oct 22 '22 19:10

KARASZI István


Your method is fine, clear and readable. To do it without jQuery, use the for (..in..) syntax:

var arr = [];
for (prop in objectLiteral) {
  arr.push(objectLiteral[prop]);
}
like image 8
Michael Berkowski Avatar answered Oct 22 '22 18:10

Michael Berkowski