Skip to main content

Command Palette

Search for a command to run...

Loop through objects keys and values in Javascript

Updated
•2 min read•View as Markdown
Loop through objects keys and values in Javascript

The various methods that can be used to loop through objects in JavaScript are:

  1. Using a for...in loop
  2. Object.keys method
  3. Object.values method
  4. Object.entries method

The For... in loop

const user = {
    name: 'John Doe',
    email: 'john.doe@example.com',
    age: 35,
    dob: '28/12/1984',
    active: true
};

// iterate over the user object
for (const key in user) {
    if (user.hasOwnProperty(key)) { // Explicitly check if the property belongs to the object or has been inherited
        console.log(`${key}: ${user[key]}`);
    }
}

// name: John Doe
// email: john.doe@example.com
// age: 35
// dob: 28/12/1984
// active: true

The object.keys() method

It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.

const courses = {
    java: 10,
    javascript: 55,
    nodejs: 5,
    php: 15
};

// convert object to key's array
const keys = Object.keys(courses);
console.log(keys);

// [ 'java', 'javascript', 'nodejs', 'php' ]

// iterate over object
keys.forEach((key, index) => {
    console.log(`${key}: ${courses[key]}`);
});

// java: 10
// javascript: 55
// nodejs: 5
// php: 15

The Object.values() method

It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

const animals = {
    tiger: 1,
    cat: 2,
    monkey: 3,
    elephant: 4
};

Object.values(animals).forEach(val => console.log(val)); // iterate over object values

// 1
// 2
// 3
// 4

The Object.entries() method

Object.entries() outputs an array of arrays, with each inner array having two elements. The first element being the property and the second element is the value.

const animals = {
    tiger: 1,
    cat: 2,
    monkey: 3,
    elephant: 4
};

const entries = Object.entries(animals);
console.log(entries);

// [ [ 'tiger', 1 ],
//   [ 'cat', 2 ],
//   [ 'monkey', 3 ],
//   [ 'elephant', 4 ] ]

AND to loop over the array returned by Object.entries(), you can either use the for...of loop or the forEach() method as shown below:


for (const [key, value] of Object.entries(animals)) { // for...of loop
    console.log(`${key}: ${value}`);
}

OR

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

More from this blog

I

Is A Web Learning

54 posts