Home » Programming » Javascript » Javascript Convert Object To Array

How to Convert an Object to an Array in JavaScript [Examples]

This article will show you the ways to convert an object to an array in JavaScript – quickly and easily.

There are many ways to convert objects to arrays, but these (should) be the most straightforward methods.

Converting Object to Array in JavaScript – Values Only

If you only need the values from the object, the Object.values() method will extract them into an array:

var myObject = {
    colour: 'blue',
    number: 43,
    name: 'Fred',
    enabled: true
};
var values = Object.values(myObject);

console.log(values);

The above will return an array with only the values from the object:

[ "blue", 43, "Fred", true ]

Keys and Values as Array Pairs

If you want both the keys (or names, or attributes, or whatever terminology you use) and values of the object, you can get each of them as a key/value pair in an array using Object.entries():

var myObject = {
    colour: 'blue',
    number: 43,
    name: 'Fred',
    enabled: true
};
var keyValuePairs = Object.entries(myObject);

console.log(keyValuePairs);

The above will return an array containing arrays, each of them containing the key and value from the original object:

    ?[
       ?[ "colour", "blue" ],
       ?[ "number", 43 ],
       ??[ "name", "Fred" ],
       ??[ "enabled", true ]
?    ]

Associative Arrays (Hashes) in JavaScript

Javascript does not support associative arrays (known otherwise as hashes). PHP and other programming languages support this functionality – which allows you to use strings as array keys/indexes – JavaScript does not. In JavaScript, only numerical indexes are supported in arrays – the only alternative is to use objects to store your data.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment