How To Convert Object To Array In Javascript

In order to design interactive and dynamic user interfaces for websites, a lot of programmers employ JavaScript. The object is one of JavaScript’s primary data types for storing key-value pairs. In contrast, arrays are used to hold elements in a specific order.

In JavaScript, you may need to turn an object into an array at times. This is handy when you wish to conduct actions on an object’s keys or values as if they were an array.

Fortunately, JavaScript includes various methods for converting an object to an array.

Let’s dive!

Why Is There A Need to convert object to array in javascript

Conversion of an object to an array in javascript is required for a variety of reasons. Among the primary reasons are:

  • To Loop Through Object: Looping through an object in JavaScript is more complicated than looping through an array. An object’s contents may be more easily looped through if it is converted to an array.
  • To Use Array Methods: JavaScript arrays provide a number of built-in methods that can help you manipulate their contents more easily.
  • To Sort Object Properties: You have to convert an object to an array if you wish to utilize JavaScript’s built-in sorting functions to arrange an object’s properties in an array according to their keys or values.
  • To Filter Object Properties: If you need to filter the properties of an object based on certain criteria, converting the object to an array can make this task easier.
  • To Perform Mathematical Operations: Arrays in JavaScript are particularly useful for performing mathematical operations on their contents.

Approaches to convert object to array in javascript

There are four methods, how to change an object to an array in javascript. Methods are listed below:-

  1. Using Object.keys() and Array.map() Method
  2. Using Object.entries() Method
  3. Using Object.getOwnPropertyNames() and Array.map() Method
  4. Using for…in Loop

Let’s have a look.

1. Using Object.keys() and Array.map() Method

Object.keys() method returns an array of keys of an object and by running a specific function on each element of the parent array, the JavaScript map() method builds an array. It is a method without mutation. The map() method is typically used to loop through an array and call a function on each entry.

Here’s how it works.

Source Code:-

const object = {name: ‘Anupam’, age: 21, city: ‘Gurugram’};

//here we are using the function
const arr = Object.keys(object).map(key => [key, object[key]]);

console.log(arr);

Output:-

[["name", "Anupam"], ["age", 21], ["city", "Gurugram"]]

Explanation of code:-

  • In the beginning, we build an object called “object” with the three properties name, age, and city.
  • The Object.keys() is used to get the object’s keys and returns an array. An array of keys, in this case [“name,” “age,” and “city,” is returned by this procedure.
  • Then, after iterating through the key array, we build a new array for every key using the Array.map(). The key-value pair is contained in each new array as an array with two entries.
  • A key-value pair from the original object is represented by each of the three sub-arrays in the array arr, which is the last array we have.

2. Using Object.entries() Method

Objects.entries() is used to convert an object in an array of key and value pairs.

 Here’s how it works:

Source Code:-

const object = {name: ‘Dhoni’’, age: 41, city: ‘Ranchi’};

//here we are using the function
const arr = Object.entries(object);

console.log(arr)

Output:-

[["name", "Dhoni"], ["age", 41], ["city", "Ranchi"]]

Explanation of code:-

  • ‘name’, ‘age’ and ‘city’ are the three characteristics we provide the object ‘object’.
  • Object.entries() used to convert the object into an array of key-value pairs. This method returns an array of sub-arrays, each having a key-value pair from the original object.
  • A key-value pair from the original object is represented by each of the three sub-arrays in the array arr, which is the last array we have.

3. Using Object.getOwnPropertyNames() and Array.map() Method

This strategy is identical to approach 1, but we use Object.getOwnPropertyNames() instead of Object.keys().

 Here’s how it works:

Sample Code:-

const object = {name: ‘Anuradha’, age: 22, city: ‘Lucknow’};

//here we are using the function
const arr = Object.getOwnPropertyNames(object).map(key => [key, object[key]]);

console.log(arr); 

Output:-

[["name", "Anuradha"], ["age", 22], ["city", "Lucknow"]]

Explanation of code:-

  • The first thing we do is construct an object called obj with the three properties name, age, and city.
  • The keys of the object are extracted as an array by using the Object.getOwnPropertyNames( ). An array of keys, in this case [“name,” “age,” and “city,” is returned by this procedure.
  • Then we use Array.map() to create a new array.
  •  The key-value pair is contained in each new array as an array with two entries.
  • A key-value pair from the original object is represented by each of the three sub-arrays in the array arr, which is the last array we have.

4. Using for…in Loop

This approach involves using a for…in loop to iterate over the properties of an object and push each key-value pair as an array into a new array.

Here’s how it works:

Sample Code:-

const object = {name: ‘Loura’, age: 67, city: 'London'};
const arr = [];

for (let key in object) {
  arr.push([key, object[key]]);
}
console.log(arr)

Output:-

[["name", "Loura"], ["age", 67], ["city", "London"]]

Explanation of code:-

  • The first thing we do is construct an object called obj with the three properties name, age, and city.
  • Then we create an empty array ‘arr’.
  • Using ‘for…in’ loop to iterate in ‘object’ using key function to fetch key and then push that key in ‘arr’.

Best approach:- Using Object.entries() Method

Using Object.entries() method is the most concise and straightforward way to convert an object into an array of key-value pairs.

Here’s why:

  • Simplicity: This is the simplest and most succinct, using only one line of code.
  • Readability: The use of the Object.entries() function clarifies what is happening in the code because it is a built-in method developed expressly for this reason.
  • Flexibility: The Object.entries() method returns an array of sub-arrays, therefore it may be utilized in other array methods like map(), reduce(), filter(), and so on.
  • Performance: This approach is faster than using a for…in loop or Object.keys() method, especially for large objects.

Sample Problem how to convert object to array in JavaScript

Sample Problem 1:- Using Object.keys() and Array.map() Method

Problem statement:- Samreen is working on a project where she needs to display a list of products with their details, such as name, price, and description. The product details are stored as an object in the following format given as ‘products’:

Solution Code:-

const products = {
  "product_1": { name: "Product A", price: 500, description: "Description for Product A" },
  "product_2": { name: "Product B", price: 650, description: "Description for Product B" },
  "product_3": { name: "Product C", price: 700, description: "Description for Product C" }
};

const productsArray = Object.keys(products).map(key => {
  const product = products[key];
  product.id = key;
  return product;
});
console.log(productsArray);

Output:-

[
  { name: 'Product A', price: 500, description: 'Description for Product A', id: 'product_1' },
  { name: 'Product B', price: 650, description: 'Description for Product B', id: 'product_2' },
  { name: 'Product C', price: 700, description: 'Description for Product C', id: 'product_3' }
]

Explanation:-

  • The code initializes an object called products with three product items.
  • The Object.keys() method is used to construct an array of the products object’s keys.
  • The map() method is called on the keys array to create a new array.
  • The map() method accepts an array as an input and returns a new element after applying a function to each element.
  • The function declares a new variable called product and associates the value of the product’s object attribute with the key of the current array member.
  • A new property called id is added to the product object with the value of the current key.
  • The modified product object is returned as an element of the new array.
  • The new array is assigned to a variable called productsArray.
  • The contents of the productsArray variable are printed to the console using console.log().

Sample Problem 2:- Using Object.entries() Method

Problem statement:- Assume you are working on a project for a property management real estate company. You have an object called “properties” that lists details about each property, including its name, address, and monthly rent. The information about the properties must be organized into an array of objects along with a special ID for each property. You choose to utilize the Object.entries() function to achieve this. Here is an illustration of some code:

Solution Code:-

const properties = {
  "property_1": { name: "Property A", address: "323 Main St", rent: 1000 },
  "property_2": { name: "Property B", address: "656 Elm St", rent: 1800 },
  "property_3": { name: "Property C", address: "989 Oak St", rent: 2200 }
};

const propertiesArray = Object.entries(properties).map(([key, value]) => {
  return { id: key, ...value };
});

console.log(propertiesArray);

Output:-

[
  { id: "property_1", name: "Property A", address: "323 Main St", rent: 1000 },
  { id: "property_2", name: "Property B", address: "656 Elm St", rent: 1800 },
  { id: "property_3", name: "Property C", address: "989 Oak St", rent: 2200 }
]

Explanation:-

  • An object called properties, which includes details on rental properties, is defined in the code.
  • An array of key-value pairs is created from the properties object using Object.entries().
  • On the output array, the map() is used to generate a new array which contains objects.
  • The map() method uses square bracket notation to destructure the key and value for each key-value pair in the array.
  • The id property is set to the current key when creating a new object, and the other attributes are spread out using the spread operator.
  • As a component of the fresh array, the new object is returned.
  • Using console.log(), the array’s updated property objects with the new id property are sent to the console.

Sample Problem 3:- Using Object.getOwnPropertyNames() and Array.map() Method

Problem statement:- When creating an online store, you must present a list of products together with their costs, reviews, and descriptions. The data is returned from the server as an object with each key representing a product ID and its value containing the product details.

Solution:-

Solution Code:-

// Sample data from server
const data = {
  product_1: { name: "Product A", price: 40, rating: 4, description: "Product A  description" },
  product_2: { name: "Product B", price: 120, rating: 3.5, description: "Product B description" },
  product_3: { name: "Product C", price: 85, rating: 4.2, description: "Product C description" }
};

const productIds = Object.getOwnPropertyNames(data);

const products = productIds.map(productId => {
  const product = data[productId];
  return {
    id: productId,
    name: product.name,
    price: product.price,
    rating: product.rating,
    description: product.description
  };
});
console.log(products)

Output:-

[
  { id: 'product_1', name: 'Product A', price: 40, rating: 4, description: 'Product A description' },
  { id: 'product_2', name: 'Product B', price: 120, rating: 3.5, description: 'Product B description' },
  { id: 'product_3', name: 'Product C', price: 85, rating: 4.2, description: 'Product C description' }
]

Explanation:-

  • Object.getOwnPropertyNames() function is used to get an array of keys from the data object.
  • Each key is converted into an object with the original key-value pairs and an additional id property using the Array.map() function.
  • Objects containing the original key-value pairs and the newly added id attribute are present in the array products as well.

Sample Problem 4:- Using for…in Loop

Problem statement:- Jitesh gets the task to develop a web application and to fetch data using REST API. The data fetched will be in Json format and must be converted into an array of objects before shown in the user interface. Help him with the code.

Solution:-

Solution Code:-

const data = { 
  "user_1": { "name": "Jitesh", "age":  21, "city": "Greater Noida" },
  "user_2": { "name": "Fahad", "age": 22, "city": "Noida" },
  "user_3": { "name": "Zaid", "age": 45, "city": "Delhi" }
};

const arr = [];
for (let key in data) {
  const obj = data[key];
  obj.id = key;
  arr.push(obj);
}
console.log(arr)

Output:-

[
  { id: "user_1", name: "Jitesh", age: 21, city: "Greater Noida" },
  { id: "user_2", name: "Fahad", age: 22, city:”Noida” },
  { id: "user_3", name: "Zaid", age: 45, city: "Delhi" }
]

Explanation:-

  • We use a for…in loop to iterate over the properties of the data object.
  • Inside the loop, we assign each object to a new variable obj and add an id property to it, which we set to the key.
  • We push each modified object into the arr array.

Conclusion

We talked about many methods for changing a JavaScript object into an array. The choice of strategy relies on the particular use case and requirements.

Before selecting a method, it is critical to understand the distinctions between them and to consider considerations such as performance, readability, and maintainability. Additionally, we learned how to put each strategy into practice by looking at sample code and its results.

Finally, the ability to convert objects to arrays is a critical skill for JavaScript developers. The quality and effectiveness of code can be increased by comprehending the various approaches that are available and choosing the optimal one for a particular use case.