How to use a for…in loop In Javascript
Using a for…in loop, iterate over keys of the object. For each key, verify if it belongs to the object itself (not its prototype). If so, create an object with the key-value pair and push it into an array. This process ensures only own properties are included in the resulting array of objects.
Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}
Example: In this example we iterates myObject keys using a for…in loop, creates objects for each key-value pair, pushes them to arrayOfObjects, and logs it.
const myObject = {
key1: "HTML",
key2: "CSS",
key3: "JavaScript",
};
const arrayOfObjects = [];
for (let key in myObject) {
if (myObject.hasOwnProperty(key)) {
let obj = {};
obj[key] = myObject[key];
arrayOfObjects.push(obj);
}
}
console.log(arrayOfObjects);
Output
[ { key1: 'HTML' }, { key2: 'CSS' }, { key3: 'JavaScript' } ]
How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object.