How To Convert Object To Array In Javascript

In JavaScript, objects are a fundamental data type that allows developers to store key-value pairs. Although they are incredibly useful, there are times when you might want to convert an object into an array to take advantage of array-specific methods or for easier manipulation of the data.

In this blog post, we will discuss multiple ways to convert an object to an array in JavaScript, and we will provide examples to illustrate each method. Let’s dive in!

1. Using Object.entries() method

The Object.entries() method is a built-in JavaScript function that returns an array of an object’s key-value pairs in the format [key, value]. Here’s an example:

    const obj = {
        name: "John",
        age: 28,
        city: "New York"
    };

    const array = Object.entries(obj);
    console.log(array);
    // Output: [['name', 'John'], ['age', 28], ['city', 'New York']]
    

2. Using Object.keys() method

The Object.keys() method returns an array of the object’s keys. You can use it in combination with the map() function to create an array of key-value pairs:

    const obj = {
        name: "John",
        age: 28,
        city: "New York"
    };

    const array = Object.keys(obj).map(key => [key, obj[key]]);
    console.log(array);
    // Output: [['name', 'John'], ['age', 28], ['city', 'New York']]
    

3. Using Object.values() method

If you are only interested in the values of the object and not the keys, you can use the Object.values() method. This method returns an array of the object’s values:

    const obj = {
        name: "John",
        age: 28,
        city: "New York"
    };

    const array = Object.values(obj);
    console.log(array);
    // Output: ['John', 28, 'New York']
    

4. Using a for…in loop

Another way to convert an object to an array is by using a for…in loop. This loop iterates over the keys of the object, allowing you to create an array of key-value pairs:

    const obj = {
        name: "John",
        age: 28,
        city: "New York"
    };

    const array = [];
    for (const key in obj) {
        array.push([key, obj[key]]);
    }

    console.log(array);
    // Output: [['name', 'John'], ['age', 28], ['city', 'New York']]
    

To summarize, JavaScript provides various ways to convert an object into an array, depending on your specific requirements. Each method has its own advantages, and it’s essential to choose the one that best fits your needs. Happy coding!