Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, transform object into array

I've got an object:

var obj = {     "Mike": 24,     "Peter": 23,     "Simon": 33,     "Tom": 12,     "Frank": 31 }; 

I want to create an array that holds the values of the object. The keys (key names) can be disregarded:

[24, 23, 33, 12, 31] 

The order of the values is NOT important!

One solution (obviously) would be do have a function that takes the values and puts them into an array:

var arr = valuesToArray(obj);  

I will accept such a function as the answer. However, I would be more pleased if there would be an API function (ECMAScript, jQuery, browser-specific, ...) that could do this. Is there such a thing?

like image 855
Šime Vidas Avatar asked Jan 05 '11 18:01

Šime Vidas


People also ask

How do you transform an object to 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 in JavaScript?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');

What array will you get if you convert an object to array?

If an object is converted to an array, the result is an array whose elements are the object's properties.

Which is the valid example for object Fromentries () method?

Example 1: Conversion of a Map into an Object. Example 2: Conversion of a Array into an Object. Supported Browsers: The browsers supported by Object.


1 Answers

The obvious way would be to do a for-in loop, as @quixoto suggests, but just for the record, and since you are looking for a built-in way, you could pair the new ECMAScript 5 methods Object.keys and Array.prototype.map, available on latest browsers:

function valuesToArray(obj) {   return Object.keys(obj).map(function (key) { return obj[key]; }); } 

UPDATE: ES2017 introduced the Object.values method, which does exactly what you want.

Additionally, ES2017 adds another often useful method, Object.entries. This method returns an array of key-value pairs.

const obj = {      "Mike": 24,      "Peter": 23,      "Simon": 33,      "Tom": 12,      "Frank": 31  };    const values = Object.values(obj);  const entries = Object.entries(obj);  console.log('values:', values);  console.log('entries:', entries);
like image 112
Christian C. Salvadó Avatar answered Oct 05 '22 03:10

Christian C. Salvadó