How to use for…in Loop In Javascript
The for…in loop in JavaScript iterates over the keys of the object, and by checking for hasOwnProperty, it makes sure that only the object’s properties are considered. Values corresponding to each key are pushed into an array, converting the original object into an array of objects.
Syntax:
const arrayOfObjects = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
arrayOfObjects.push(obj[key]);
}
}
Example: The below code uses the for…in Loop to convert an object into an Array of objects using JavaScript.
const arr = {
java: {
id: 1,
title: "Java Programming",
},
python: {
id: 2,
title: "Python for Beginners",
},
};
const res = [];
for (let key in arr) {
if (arr.hasOwnProperty(key)) {
res.push(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()