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?
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');
If an object is converted to an array, the result is an array whose elements are the object's properties.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With