How can I convert a JavaScript object to an array of key-value pairs using Object.entries()?
Richard W
richard w profile pic

To convert a JavaScript object to an array of key-value pairs, you can use theObject.entries() method. TheObject.entries() method returns an array of arrays, where each inner array contains a key-value pair from the object. Here's an example of how you can do it:

1
2
3
4
5
6
7

const obj = { name: 'John', age: 30, city: 'New York' };

const entries = Object.entries(obj);

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

In the example above, theObject.entries() method is used to convert theobj object into an array of key-value pairs stored in theentries variable. Each inner array inentries contains a key-value pair from the original object. You can then iterate over theentries array using array methods likeforEach(),map(), or a for loop to access and manipulate each key-value pair individually. For example:

1
2
3
4
5
6
7
8

entries.forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
// Output:
// name: John
// age: 30
// city: New York

In the above example, theforEach() method is used to iterate over each inner array in theentries array. The destructuring assignment[key, value] is used to extract the key and value from each inner array, which are then used to print each key-value pair. By usingObject.entries(), you can easily convert a JavaScript object into an array of key-value pairs, enabling you to perform various operations or transformations on the object's properties.