object to array javascript

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:

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:

[
  { 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:

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

const myArr = Object.entries(myObj);

console.log(myArr);

This will output:

[
  ["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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe