Skip to main content

Command Palette

Search for a command to run...

How to loop thorough object keys and values in JavaScript.

Published
1 min read
How to loop thorough object keys and values in JavaScript.
D

Hello folks ! Myself Deepak . I'm a student and aspiring Blockchain developer.

Example:

const userProfile = {
    id: 1,
    name: Deepak Agashe,
    age: 20,
    title: 'Frontend Web Developer', 
};

Object.keys method

object.keys(userProfile).forEach((key) => {
    console.log(`${key}: ${userProfile[key]}`);
});

Object.keys method returns an array of keys. We run forEach loop on array returned by Object.keys method

We display the value of a key using square bracket syntax.

Object.values method

Object.values(userProfile).forEach((value) => {
    console.log('Value: ',value);
});

Object.values method returns an array of values of that object. We run forEach loop on the array returned by Object.values method.

Object.entries method

Object.entries(userProfile).forEach(([key,value]) => {
    console.log(`${key}: ${userProfile[key]}`);
});

Object.entries method returns an array of an array. We run forEach loop and destructure the parameter [key, value] of an array.

For ..in loop

for (const key in userProfile) {
    console.log(`${key}: ${userProfile[key]}`);
}