You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

For-of with Object.keys() alternative:

var p = {
    0: "value1",
    "b": "value2",
    key: "value3"
};

for (var key of Object.keys(p)) {
    console.log(key + " -> " + p[key])
}

Notice the use of for-of instead of for-in, if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object's own properties without the whole prototype-chain properties

Using the new Object.entries() method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

const p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (const [key, value] of Object.entries(p)) {
  console.log(`{value}`);
}
Answer from levik on Stack Overflow
Top answer
1 of 12
5196

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

For-of with Object.keys() alternative:

var p = {
    0: "value1",
    "b": "value2",
    key: "value3"
};

for (var key of Object.keys(p)) {
    console.log(key + " -> " + p[key])
}

Notice the use of for-of instead of for-in, if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object's own properties without the whole prototype-chain properties

Using the new Object.entries() method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

const p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (const [key, value] of Object.entries(p)) {
  console.log(`{value}`);
}
2 of 12
1385

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

ECMAScript 6 adds for...of:

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

ECMAScript 8 adds Object.entries() which avoids having to look up each value in the original object:

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

You can combine for...of, destructuring, and Object.entries:

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

Both Object.keys() and Object.entries() iterate properties in the same order as a for...in loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.

🌐
freeCodeCamp
freecodecamp.org › news › how-to-iterate-over-objects-in-javascript
Loop Through an Object in JavaScript – How to Iterate Over an Object in JS
November 7, 2024 - It takes the object we want to loop over as an argument and returns an array containing all property names (also known as keys). const population = { male: 4, female: 93, others: 10 }; let genders = Object.keys(population); console.log(genders); // ["male","female","others"] This now gives us the advantage of applying any array looping method to iterate through the array and retrieve the value of each property:
Discussions

loops - How to iterate over a JavaScript object? - Stack Overflow
When you iterate over an object there is no guarantee to the order in which they will appear. ... Does this answer your question? How to loop through a plain JavaScript object with the objects as members? ... modern ECMAScript specification: array indices first in ascending order by value, then ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Iterate over Object Literal Values - Stack Overflow
We can use Object.keys(x) to return an array of all of the keys within our object. ... Now we able to map, filter, reduce and loop over our array and do something with that value within our object: More on stackoverflow.com
🌐 stackoverflow.com
javascript - Iterate over values of object - Stack Overflow
I want to iterate over all values of a map. I know it's possible to iterate over all keys. But is it possible to iterate directly over the values? var map = { key1 : 'value1', key2 : 'value2' } ... More on stackoverflow.com
🌐 stackoverflow.com
Why You Should Prefer Map Over Object In JavaScript
A very thorough and in-depth article! I tend towards a similar break-out as you described -- object literals for data that has fixed keys known at compile time and Map for mutable key/value pairs that are going to be frequently added or deleted at runtime. The point about finding the number of object keys being O(n) becomes less of an issue, since in most cases you should know the keys up-front. I wish Map was more ergonomic though, because it's still lacking in a few areas: Initializing with values is awkward. You pass it an array of arrays, where the inner arrays must be length 2. Ideally, this would be a tuple but JavaScript lacks those. There's no uniqueness check on the provided keys, if the arrays are more than length 2 the extra elements are silently dropped. A fun one is if you do let m = new Map([[, 4]]) then calling m.get() with no arguments brings back the value 4. Not saying that this doesn't make sense in the context of JavaScript, but the whole "array of tuples" initialization is awkward. It would be nice to be able to use an object literal in the Map constructor, which is a more familiar way of initializing key/value data. 2. Map is missing some conveniences with TypeScript, for example that Map.prototype.get still returns T | undefined even after checking that the key exists with has. 3. Missing many utilities functions. We can iterate over Map key/value pairs, so we should be able to .filter, .map, and all other normal things that you do with iterators. The methods available on the Map prototype are lacking compared with other languages. Overall, people often do whatever is most convenient, even if it's not the "right" choice, and the fact that object literals have a convenient syntax and Map doesn't might be what drives the decision despite the valid points raised in the article. More on reddit.com
🌐 r/javascript
73
203
July 20, 2022
People also ask

How can I iterate over an object entries while preserving the order of keys?
Objects in JavaScript are unordered by default, and the order of keys is not guaranteed. If you need to iterate over an object's properties in a specific order, you have a few options: - Use the Object.entries() method to get an array of \[key, value\] pairs, sort the array based on the keys, and then iterate over the sorted array. - Create an array of keys in the desired order and then access the corresponding values from the object using those keys. - Use a Map instead of an object, as Map maintains the insertion order of key-value pairs. You can convert an object to a Map using new M
🌐
latenode.com
latenode.com › home › blog › how to iterate over a javascript object?
How to Iterate Over a JavaScript Object? - Latenode Blog
Are there any other libraries or methods for object iteration?
Yes, there are several other libraries and methods that provide utilities for object iteration. Some popular ones include: - Underscore.js: Provides the _.each() method for iterating over objects. - Lodash: Offers various methods like _.forOwn(), _.forIn(), and _.forEach() for object iteration. - jQuery: Has the $.each() method that can be used for iterating over objects. These libraries offer additional functionality and can be helpful if you are already using them in your project. However, if you only need basic object iteration, the native JavaScript methods discussed in this articl
🌐
latenode.com
latenode.com › home › blog › how to iterate over a javascript object?
How to Iterate Over a JavaScript Object? - Latenode Blog
Can I use arrow functions with these iteration methods?
Yes, you can use arrow functions with methods like map(), forEach(), and _.forOwn(). Arrow functions provide a concise syntax for writing function expressions. For example: ``` Object.entries(person).map(([key, value]) => {  console.log(key + ': ' + value); }); ``` However, keep in mind that arrow functions have a lexical this binding, which means they inherit the this value from the surrounding scope. If you need to access the this context within the iteration callback, you may need to use a regular function expression instead.
🌐
latenode.com
latenode.com › home › blog › how to iterate over a javascript object?
How to Iterate Over a JavaScript Object? - Latenode Blog
Top answer
1 of 16
2609

Iterating over properties requires this additional hasOwnProperty check:

for (var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
        // do stuff
    }
}

It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of obj.

hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class.


It's also possible to call hasOwnProperty through the object itself:

if (obj.hasOwnProperty(prop)) {
    // do stuff
}

But this will fail if the object has an unrelated field with the same name:

var obj = { foo: 42, hasOwnProperty: 'lol' };
obj.hasOwnProperty('foo');  // TypeError: hasOwnProperty is not a function

That's why it's safer to call it through Object.prototype instead:

var obj = { foo: 42, hasOwnProperty: 'lol' };
Object.prototype.hasOwnProperty.call(obj, 'foo');  // true
2 of 16
1346

As of JavaScript 1.8.5 you can use Object.keys(obj) to get an Array of properties defined on the object itself (the ones that return true for obj.hasOwnProperty(key)).

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

This is better (and more readable) than using a for-in loop.

Its supported on these browsers:

  • Firefox (Gecko): 4 (2.0)
  • Chrome: 5
  • Internet Explorer: 9

See the Mozilla Developer Network Object.keys()'s reference for futher information.

Top answer
1 of 16
1344

For iterating on keys of Arrays, Strings, or Objects, use for .. in :

for (let key in yourobject) {
  console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
    console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (let key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}

You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {}).

This MDN documentation explains more generally how to deal with objects and their properties.

If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

let keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

 let keys = [];
 for (let key in yourobject) {      
     if (yourobject.hasOwnProperty(key)) keys.push(key);
 }

Then you can iterate on your properties by index: yourobject[keys[i]] :

for (let i=300; i < keys.length && i < 600; i++) { 
   console.log(keys[i], yourobject[keys[i]]);
}
2 of 16
101

Here is another iteration solution for modern browsers:

Object.keys(obj)
  .filter((k, i) => i >= 100 && i < 300)
  .forEach(k => console.log(obj[k]));

Or without the filter function:

Object.keys(obj).forEach((k, i) => {
    if (i >= 100 && i < 300) {
        console.log(obj[k]);
    }
});

However you must consider that properties in JavaScript object are not sorted, i.e. have no order.

🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › foreach-object
Iterating Through an Object with `forEach()` - Mastering JS
You can iterate through both keys ... Jean-Luc Picard" followed by "rank Captain" Object.entries(obj).forEach(entry => { const [key, value] = entry; console.log(key, value); });...
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...in
for...in - JavaScript | MDN - MDN Web Docs
The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.
🌐
Latenode
latenode.com › home › blog › how to iterate over a javascript object?
How to Iterate Over a JavaScript Object? - Latenode Blog
September 3, 2026 - Using Object.values() allows you to iterate over an object's values directly.
🌐
W3Schools
w3schools.com › js › js_object_iterations.asp
JavaScript Object Iterations
The fromEntries() method creates an object from a list of key/value pairs.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › entries
Object.entries() - JavaScript - MDN Web Docs
4 days ago - Using array destructuring, you can iterate through objects easily. ... // Using for...of loop const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of Object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // Using array methods Object.entries(obj).forEach(([key, ...
🌐
Mimo
mimo.org › tutorials › javascript › how-to-loop-through-an-object-in-javascript
How to Loop Through an Object in JavaScript
Learn how to loop through an object in JavaScript using Object.entries(), Object.keys(), and Object.values() for keys, values, and key-value pairs.
🌐
Attacomsian
attacomsian.com › blog › javascript-iterate-objects
How to iterate over object keys and values in JavaScript
November 12, 2022 - Learn how to use the for...in statement, Object.keys(), Object.values(), and Object.entries() methods to iterate over object properties in JavaScript.
🌐
DEV Community
dev.to › fpaghar › object-iteration-ways-in-javascript-pej
Object Iteration ways in JavaScript - DEV Community
April 8, 2024 - In this example, the property with the symbol key Symbol('b') is ignored, and only the values of properties a and c are returned. Object.getOwnPropertyNames() is a method in JavaScript used to iterate over the properties of an object.
🌐
Hostman
hostman.com › tutorials › looping-through-objects-s-keys-and-values-in-javascript
How to loop through objects keys and values in Javascript? | Hostman
The for loop feature for iterating through object keys and values in JS provides quick access to the properties and the ability to manipulate them within an object. By understanding the syntax and usage of the feature, you can improve the ...
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › iterate-object
How to Iterate Over a JavaScript Object - Mastering JS
How do you iterate over the key/value pairs and print out "name: Luke Skywalker", "title: Jedi Knight", and "age: 23"? There are a lot of ways to do this in modern JavaScript. Here's 3 different ways: The Object.entries() function returns an arrau coontaining the object's key/value pairs.
🌐
Medium
sunnygandhi01.medium.com › how-to-iterate-through-an-object-keys-and-values-in-javascript-d8bb464615fa
How to Iterate through an object keys and values in JavaScript. | by Sunnygandhi | Medium
January 13, 2021 - Keys() method was introduced in ES6 to make it easier to iterate over objects. Later with ES8, there were two new methods were added, Object. Entries() and Object. Values(). The newest methods convert the object into an array and then use array looping methods to iterate over that array.
🌐
Index.dev
index.dev › blog › javascript-object-iteration-methods
10 Effective Methods to Iterate Over JavaScript Objects
It only iterates over the object’s own properties, ignoring the prototype properties. Cleaner and more modern than for...in. Slightly less intuitive for beginners because it involves array methods. ... Object.values() if the values are all that matter to you and the keys are not.
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals
How to Iterate Over Object Properties in JavaScript | Envato Tuts+
January 19, 2022 - Let's take a look at some of the modern ways to iterate over an object's properties in JavaScript. Object.keys() returns an array containing the keys of all properties on any given object. So we can combine Object.keys() with a for loop to iterate over all the properties of an object by iterating over its keys like so: Because our iterator gives us the keys to the object properties, we are able to access the values directly from the object user using the property accessor syntax: user[key].