How To Object To Array In Javascript

When working with JavaScript, you may come across a situation where you need to convert an object to an array.
This can be useful for various reasons, such as when you need to perform operations like mapping or filtering
that are only available for arrays. In this blog post, we will explore different methods to achieve this conversion.

Using Object.keys, Object.values, or Object.entries

One of the simplest ways to convert an object to an array is by using the built-in JavaScript methods
Object.keys, Object.values, or Object.entries. Each of these methods
return an array and can be used depending on whether you want an array of the object’s keys, values, or both.

Example 1: Using Object.keys

Convert an object to an array containing its keys:

const object1 = {
  a: "one",
  b: "two",
  c: "three"
};

const array1 = Object.keys(object1);
console.log(array1);
// Output: ["a", "b", "c"]

Example 2: Using Object.values

Convert an object to an array containing its values:

const object2 = {
  a: "one",
  b: "two",
  c: "three"
};

const array2 = Object.values(object2);
console.log(array2);
// Output: ["one", "two", "three"]

Example 3: Using Object.entries

Convert an object to an array containing its key-value pairs:

const object3 = {
  a: "one",
  b: "two",
  c: "three"
};

const array3 = Object.entries(object3);
console.log(array3);
// Output: [["a", "one"], ["b", "two"], ["c", "three"]]

Using a for…in loop

Another way to convert an object to an array is by using a for...in loop. This method can give you
more flexibility if you need to manipulate the data during the conversion process.

Example 4: Using a for…in loop to convert an object to an array

const object4 = {
  a: "one",
  b: "two",
  c: "three"
};

const array4 = [];

for (const key in object4) {
  if (object4.hasOwnProperty(key)) {
    array4.push([key, object4[key]]);
  }
}

console.log(array4);
// Output: [["a", "one"], ["b", "two"], ["c", "three"]]

Conclusion

Converting an object to an array in JavaScript can be done using various methods, such as
Object.keys, Object.values, Object.entries, or a for...in loop.
Depending on your requirements and the specific data you’re working with, you can choose the method that best
suits your needs.