Skip to content
the poor coder

object to array javascript

Poor Man
Published
Reading time
1 min read
On this page

Object to Array in JavaScript#

If you are working with JavaScript, you might need to convert an object into an array. There are several ways to do it. Let's explore some of them.

Using Object.keys() and Array.map()#

The easiest and simplest way to convert an object into an array is to use the Object.keys() method and the Array.map() method. Here's how:

Text
const myObj = {
  name: "Raju",
  age: 25,
  city: "New York"
};

const myArr = Object.keys(myObj).map(key => ({ key, value: myObj[key] }));

console.log(myArr);

This will output:

Text
[
  { key: "name", value: "Raju" },
  { key: "age", value: 25 },
  { key: "city", value: "New York" }
]

Here, we first get all the keys of the object using Object.keys(). This returns an array of keys. We then map over this array and create a new array of key-value pairs using Array.map().

Using Object.entries()#

Another way to convert an object into an array is to use the Object.entries() method. This method returns an array of key-value pairs. Here's an example:

Text
const myObj = {
  name: "Raju",
  age: 25,
  city: "New York"
};

const myArr = Object.entries(myObj);

console.log(myArr);

This will output:

Text
[
  ["name", "Raju"],
  ["age", 25],
  ["city", "New York"]
]

Here, we directly use Object.entries() to get an array of key-value pairs.

Conclusion#

These were some of the ways to convert an object into an array in JavaScript. You can use any of these methods depending on your requirements.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC