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.

JavaScript
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.

Similar Reads

Below approaches can be used to accomplish this task

Table of Content Using Object.keys() and reduce() methodsUsing Array.from() and map() methodsUsing Object.keys() and map() methodsUsing a for…in loop...

Using Object.keys() and reduce() methods

In this approach, we are using Object.keys() and reduce() method to create an array of objects from the keys and values of an object. It iterates over keys, pushing objects into an accumulator array with key-value pairs, resulting in the desired array....

Using Array.from() and map() methods

The Array.from() method can be used with Object.entries() to convert an object’s key-value pairs into an iterable array. The map() method transforms each entry into an object, creating an array of objects representing the original object’s keys and values....

Using Object.keys() and map() methods

The Object.keys() method can be used to create an array of all the keys available in the object, then the map() method can be used to iterate over them and store them into an array as objects....

Using a for…in loop

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