How to convert an Object to an Array of key-value pairs in JavaScript?

You might have seen a situation where you have to convert an object to an array of key-value pairs in JavaScript. First of all we should have the basic knowledge about objects and arrays.

Object: Objects in JavaScript is the most important data-type, which forms the building blocks for modern JavaScript. Objects are different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Structure of objects are more complex as compare to primitive data-types and each object may contain any combination of these primitive data-types as well as reference data-types.

Array: Basically array is a collection of homogenous data-types. Its a single variable used to store the different elements. Its used when we need to use the lots of variables to store the values. So in this list of elements can be stored under a single variable and those elements can be accessed using the indices.

We can convert an object to an array of key-value pairs using the following methods:

First method: In this method we will use the Object.keys() and map() functions to achieve the desired result. First of all by using Object.keys() method we will get all the keys of the object and then we will pass these keys to map function which maps the key and corresponding value as an array.

Example:

 

Output:
[[“1”: 10], [“2”, 20], [“3”: 30], [“4”: 40]]

Second Method: In this method we will use Object.entries() function which is JavaScript’s inbuilt function. Object.entries() function returns an array of enumrable property[key, value] pairs of the object passed as a parameter. Ordering of the properties would be same as the ordering of the object. So let’s see the implementation of the same:

Example:

 

Output:
[[“1”: 10], [“2”, 20], [“3”: 30], [“4”: 40]]

So this is how the implementation would look like. Next time you can do this by yourself in very less time as you know the solutions very well.

Leave a Reply

Your email address will not be published. Required fields are marked *