How to use Object.getOwnPropertyNames() method In Javascript
This approach utilizes the Object.getOwnPropertyNames() method to extract all the property names of the object. Then, it maps over these property names and retrieves the corresponding values from the object, effectively converting the object into an array of objects.
Syntax:
const arrayOfObjects = Object.getOwnPropertyNames(obj).map(key => obj[key]);
Example: The following code demonstrates the usage of the Object.getOwnPropertyNames() method to convert an object into an array of objects in JavaScript.
const arr = {
java: {
id: 1,
title: "Java Programming",
},
python: {
id: 2,
title: "Python for Beginners",
},
};
const res = Object.getOwnPropertyNames(arr).map(
(key) => arr[key]
);
console.log(res);
Output:
[
{ id: 1, title: 'Java Programming' },
{ id: 2, title: 'Python for Beginners' }
]
How to Convert an Object into Array of Objects in JavaScript ?
Converting an object into an array of objects can be done by converting the properties and values of the object into individual objects within an array. Various approaches in JavaScript can convert an object into an Array of objects. In this article, we will explore four different approaches to converting an object into an Array of objects using JavaScript.
Table of Content
- Using Object.values() method
- Using Object.keys() method
- Using Object.entries() method
- Using for…in Loop
- Using Object.getOwnPropertyNames() method
- Using Object.values() with Array.map()