How can I convert an object to an array in JavaScript while preserving key-value pairs?
Rashid D
rashid d profile pic

To convert an object to an array in JavaScript while preserving key-value pairs, you can use theObject.entries() method, which returns an array of an object's enumerable property[key, value] pairs. Here's an example:

1
2
3
4
5
6
7
8
9
10

const obj = {
  name: "John",
  age: 30,
  occupation: "Developer"
};

const arr = Object.entries(obj);

console.log(arr);

Output:

[ ["name", "John"], ["age", 30], ["occupation", "Developer"] ]

In this example,Object.entries(obj) is called to convert theobj object into an array of its key-value pairs. The resulting arrayarr contains subarrays, where each subarray represents a key-value pair. TheObject.entries() method is supported in modern browsers and JavaScript environments. It returns the key-value pairs in the same order as they are defined in the object. Note that the array elements are themselves arrays, with the first element being the key and the second element being the value. You can then use the resulting arrayarr to perform operations such as iteration, filtering, or mapping, depending on your requirements.