W3jar
340 words
2 minutes

How to Convert JavaScript Objects to Arrays

Converting JavaScript objects to arrays is a common task, and there are various methods to do it depending on what part of the object you’re interested in. Here’s a rundown of the most common ways to achieve this:

1. Object Values to Array#

If you want to convert the values of an object into an array, you can use Object.values().

Example:

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const valuesArray = Object.values(obj);
console.log(valuesArray); // [1, 2, 3]

2. Object Keys to Array#

If you need an array of the object’s keys, use Object.keys().

Example:

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const keysArray = Object.keys(obj);
console.log(keysArray); // ['a', 'b', 'c']

3. Object Entries to Array#

To get both keys and values as an array of arrays, use Object.entries().

Example:

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const entriesArray = Object.entries(obj);
console.log(entriesArray); // [['a', 1], ['b', 2], ['c', 3]]

4. Transforming Object Properties to a Custom Array#

You might need to create a custom array based on the object’s properties. You can do this with Array.prototype.map() and Object.entries().

Example:

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const customArray = Object.entries(obj).map(
    ([key, value]) => `${key}: ${value}`
);
console.log(customArray); // ['a: 1', 'b: 2', 'c: 3']

5. Using Spread Syntax (ES6)#

While you can’t directly convert an object to an array using spread syntax, you can combine it with other methods to transform object properties into an array.

Example:

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const arrayFromObject = [...Object.entries(obj)];
console.log(arrayFromObject); // [['a', 1], ['b', 2], ['c', 3]]

6. Manual Iteration#

You can also manually iterate over the object’s properties if you need more control.

Example:

const obj = {
    a: 1,
    b: 2,
    c: 3,
};

const manualArray = [];
for (const [key, value] of Object.entries(obj)) {
    manualArray.push({ key, value });
}
console.log(manualArray); // [{key: 'a', value: 1}, {key: 'b', value: 2}, {key: 'c', value: 3}]

Each of these methods is useful depending on whether you need just the keys, just the values, or both, and whether you need to transform the data in a specific way.