How do I convert an object to an array in JavaScript?
Richard W
richard w profile pic

To convert an object to an array in JavaScript, you can use various methods and techniques. Here's a step-by-step guide on how to achieve this: 1. Create an object with key-value pairs:

1
2
3
4
5
6
7

   const obj = {
     key1: 'value1',
     key2: 'value2',
     key3: 'value3'
   };
   

2. Use theObject.entries() method: TheObject.entries() method returns an array of a given object's own enumerable property[key, value] pairs. You can use it to convert an object to an array of key-value pairs.

1
2
3
4
5

   const arr = Object.entries(obj);
   console.log(arr);
   // Output: [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]
   

3. Use theObject.keys() method in combination with themap() method: TheObject.keys() method returns an array of a given object's own enumerable property keys. You can then use themap() method to create a new array by mapping each key to its corresponding value from the object.

1
2
3
4
5

   const arr = Object.keys(obj).map(key => [key, obj[key]]);
   console.log(arr);
   // Output: [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]
   

4. Use afor...in loop to iterate over the object and construct the array: If you prefer a more manual approach, you can use afor...in loop to iterate over the object's properties and construct the array by pushing the key-value pairs.

1
2
3
4
5
6
7
8
9
10

   const arr = [];
   for (let key in obj) {
     if (obj.hasOwnProperty(key)) {
       arr.push([key, obj[key]]);
     }
   }
   console.log(arr);
   // Output: [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]
   

Choose the method that best fits your requirements and the specific context in which you need to convert an object to an array. TheObject.entries() method provides a straightforward way to achieve this conversion, while the other methods offer alternative approaches if needed.