How can I convert an object to an array of key-value pairs in JavaScript?
Antek N
In JavaScript, you can convert an object to an array of key-value pairs using various methods. Here are a few approaches:
1. Object.entries():
- TheObject.entries() method returns an array of a given object's own enumerable property[key, value] pairs.
- It allows you to convert an object into an array of key-value pairs.
In this example,Object.entries(obj) converts theobj object into an array of key-value pairs, and the resulting array (keyValuePairs) would be[['name', 'John'], ['age', 25]].
2. Object.keys() and Array.prototype.map():
- TheObject.keys() method returns an array of a given object's own enumerable property names.
- By combining it with theArray.prototype.map() method, you can create an array of key-value pairs.
In this example,Object.keys(obj) retrieves the keys of theobj object, and.map(key => [key, obj[key]]) creates an array of key-value pairs by mapping each key to an array containing the key and its corresponding value.
3. for...in loop:
- You can use afor...in loop to iterate over the object's enumerable properties and create an array of key-value pairs.
In this example, thefor...in loop iterates over the object's properties, andif (obj.hasOwnProperty(key)) ensures that only the object's own properties are considered. The loop then pushes each key-value pair as an array into thekeyValuePairs array.
These approaches allow you to convert an object to an array of key-value pairs, providing different formats for further processing or manipulation. Choose the method that best suits your use case and consider the specific requirements of your application.