[javascript] How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following:

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

Now I want to loop through all p elements (p1, p2, p3...) And get their keys and values. How can I do that?

I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval.

This question is related to javascript loops for-loop each

The answer is


_x000D_
_x000D_
    var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},_x000D_
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]_x000D_
for(var value in p) {_x000D_
    for (var key in value) {_x000D_
        if (p.hasOwnProperty(key)) {_x000D_
            console.log(key + " -> " + p[key]);_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_


for(key in p) {
  alert( p[key] );
}

Note: you can do this over arrays, but you'll iterate over the length and other properties, too.


Object.entries() function:

_x000D_
_x000D_
var p = {_x000D_
     "p1": "value1",_x000D_
     "p2": "value2",_x000D_
     "p3": "value3"_x000D_
 };_x000D_
_x000D_
for (var i in Object.entries(p)){_x000D_
 var key = Object.entries(p)[i][0];_x000D_
 var value = Object.entries(p)[i][1];_x000D_
 console.log('key['+i+']='+key+' '+'value['+i+']='+value);_x000D_
}
_x000D_
_x000D_
_x000D_


An object becomes an iterator when it implements the .next() method

_x000D_
_x000D_
const james = {
  name: 'James',
  height: `5'10"`,
  weight: 185,

  [Symbol.iterator]() {
    let properties = []
    for (let key of Object.keys(james)) {
      properties.push(key);
    }

    index = 0;
    return {
      next: () => {
        let key = properties[index];
        let value = this[key];
        let done = index >= properties.length - 1;
        index++;
        return {
          key,
          value,
          done
        };
      }
    };
  }

};


const iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
_x000D_
_x000D_
_x000D_


Using a for-of on Object.keys()

Like:

_x000D_
_x000D_
let object = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
};

for (let key of Object.keys(object)) {
  console.log(key + " : " + object[key])
}
_x000D_
_x000D_
_x000D_


Performance

Today 2020.03.06 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6

Conclusions

  • solutions based on for-in (A,B) are fast (or fastest) for all browsers for big and small objects
  • surprisingly for-of (H) solution is fast on chrome for small and big objects
  • solutions based on explicit index i (J,K) are quite fast on all browsers for small objects (for firefox also fast for big ojbects but medium fast on other browsers)
  • solutions based on iterators (D,E) are slowest and not recommended
  • solution C is slow for big objects and medium-slow for small objects

enter image description here

Details

Performance tests was performed for

  • small object - with 3 fields - you can perform test on your machine HERE
  • 'big' object - with 1000 fields - you can perform test on your machine HERE

Below snippets presents used solutions

_x000D_
_x000D_
function A(obj,s='') {_x000D_
 for (let key in obj) if (obj.hasOwnProperty(key)) s+=key+'->'+obj[key] + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function B(obj,s='') {_x000D_
 for (let key in obj) s+=key+'->'+obj[key] + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function C(obj,s='') {_x000D_
  const map = new Map(Object.entries(obj));_x000D_
 for (let [key,value] of map) s+=key+'->'+value + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function D(obj,s='') {_x000D_
  let o = { _x000D_
    ...obj,_x000D_
    *[Symbol.iterator]() {_x000D_
      for (const i of Object.keys(this)) yield [i, this[i]];    _x000D_
    }_x000D_
  }_x000D_
  for (let [key,value] of o) s+=key+'->'+value + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function E(obj,s='') {_x000D_
  let o = { _x000D_
    ...obj,_x000D_
    *[Symbol.iterator]() {yield *Object.keys(this)}_x000D_
  }_x000D_
  for (let key of o) s+=key+'->'+o[key] + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function F(obj,s='') {_x000D_
 for (let key of Object.keys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function G(obj,s='') {_x000D_
 for (let [key, value] of Object.entries(obj)) s+=key+'->'+value+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function H(obj,s='') {_x000D_
 for (let key of Object.getOwnPropertyNames(obj)) s+=key+'->'+obj[key]+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function I(obj,s='') {_x000D_
 for (const key of Reflect.ownKeys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function J(obj,s='') {_x000D_
  let keys = Object.keys(obj);_x000D_
 for(let i = 0; i < keys.length; i++){_x000D_
    let key = keys[i];_x000D_
    s+=key+'->'+obj[key]+' ';_x000D_
  }_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function K(obj,s='') {_x000D_
  var keys = Object.keys(obj), len = keys.length, i = 0;_x000D_
  while (i < len) {_x000D_
    let key = keys[i];_x000D_
    s+=key+'->'+obj[key]+' ';_x000D_
    i += 1;_x000D_
  }_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function L(obj,s='') {_x000D_
  Object.keys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function M(obj,s='') {_x000D_
  Object.entries(obj).forEach(([key, value]) => s+=key+'->'+value+' ');_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function N(obj,s='') {_x000D_
  Object.getOwnPropertyNames(obj).forEach(key => s+=key+'->'+obj[key]+' ');_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function O(obj,s='') {_x000D_
  Reflect.ownKeys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
  return s;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
let log = (name,f) => console.log(`${name} ${f(p)}`)_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('F',F);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);_x000D_
log('O',O);
_x000D_
This snippet only presents choosen solutions
_x000D_
_x000D_
_x000D_

And here are result for small objects on chrome

enter image description here


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.


You can also use Object.keys() and iterate over the object keys like below to get the value:

_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
_x000D_
Object.keys(p).forEach((key)=> {_x000D_
 console.log(key +' -> '+ p[key]);_x000D_
});
_x000D_
_x000D_
_x000D_


In latest ES script, you can do something like this:

_x000D_
_x000D_
let p = {foo: "bar"};_x000D_
for (let [key, value] of Object.entries(p)) {_x000D_
  console.log(key, value);_x000D_
}
_x000D_
_x000D_
_x000D_


Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value] pairs. As it is possible in other languages for instance Ruby.

Ok here is a code:

_x000D_
_x000D_
const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
  [Symbol.iterator]: function*() {
    for (const i of Object.keys(this)) {
      yield [i, this[i]];
    }
  }
};

for (const [k, v] of MyObject) {
  console.log(`Here is key ${k} and here is value ${v}`);
}
_x000D_
_x000D_
_x000D_

All information about how can you do an iterator and generator you can find at developer Mozilla page.

Hope It helped someone.

EDIT:

ES2017 will include Object.entries which will make iterating over [key, value] pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.

I think it is time to update my answer to let it became even more fresher than it's now.

_x000D_
_x000D_
const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
};

for (const [k, v] of Object.entries(MyObject)) {
  console.log(`Here is key ${k} and here is value ${v}`);
}
_x000D_
_x000D_
_x000D_

You can find more about usage on MDN page


Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.

At a glance here is what a JavaScript object loop look like before ECMA6:

for (var key in object) {
  if (p.hasOwnProperty(key)) {
    var value = object[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
  }
}

Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for loop. But the odd part is that this new forEach method does not support break which led to all sorts of other problems.

Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.

As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:

for (let [key, value] of Object.entries(object)) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony

Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.


If anybody needs to loop through arrayObjects with condition:

_x000D_
_x000D_
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];_x000D_
_x000D_
for (var i=0; i< arrayObjects.length; i++) {_x000D_
  console.log(arrayObjects[i]);_x000D_
  _x000D_
  for(key in arrayObjects[i]) {      _x000D_
    _x000D_
      if (key == "status" && arrayObjects[i][key] == "good") {_x000D_
        _x000D_
          console.log(key + "->" + arrayObjects[i][key]);_x000D_
      }else{_x000D_
          console.log("nothing found");_x000D_
      }_x000D_
   }_x000D_
}
_x000D_
_x000D_
_x000D_


This is how to loop through a javascript object and put the data into a table.

_x000D_
_x000D_
<body>_x000D_
<script>_x000D_
function createTable(objectArray, fields, fieldTitles) {_x000D_
  let body = document.getElementsByTagName('body')[0];_x000D_
  let tbl = document.createElement('table');_x000D_
  let thead = document.createElement('thead');_x000D_
  let thr = document.createElement('tr');_x000D_
_x000D_
  for (p in objectArray[0]){_x000D_
    let th = document.createElement('th');_x000D_
    th.appendChild(document.createTextNode(p));_x000D_
    thr.appendChild(th);_x000D_
    _x000D_
  }_x000D_
 _x000D_
  thead.appendChild(thr);_x000D_
  tbl.appendChild(thead);_x000D_
_x000D_
  let tbdy = document.createElement('tbody');_x000D_
  let tr = document.createElement('tr');_x000D_
  objectArray.forEach((object) => {_x000D_
    let n = 0;_x000D_
    let tr = document.createElement('tr');_x000D_
    for (p in objectArray[0]){_x000D_
      var td = document.createElement('td');_x000D_
      td.appendChild(document.createTextNode(object[p]));_x000D_
      tr.appendChild(td);_x000D_
      n++;_x000D_
    };_x000D_
    tbdy.appendChild(tr);    _x000D_
  });_x000D_
  tbl.appendChild(tbdy);_x000D_
  body.appendChild(tbl)_x000D_
  return tbl;_x000D_
}_x000D_
_x000D_
createTable([_x000D_
              {name: 'Banana', price: '3.04'}, // k[0]_x000D_
              {name: 'Orange', price: '2.56'},  // k[1]_x000D_
              {name: 'Apple', price: '1.45'}_x000D_
           ])_x000D_
</script>
_x000D_
_x000D_
_x000D_


Only JavaScript code without dependencies:

var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p);   // ["p1", "p2", "p3"]

for(i = 0; i < keys.length; i++){
  console.log(keys[i] + "=" + p[keys[i]]);   // p1=value1, p2=value2, p3=value3
}

The Object.keys() method returns an array of a given object's own enumerable properties. Read more about it here

_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
_x000D_
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
_x000D_
_x000D_
_x000D_


  • single level indent
  • single set of brackets
  • highest browser compatibility
  • hasOwnProperty safe

_x000D_
_x000D_
var p = {"p1": "value1", "p2": "value2", "p3": "value3"};_x000D_
_x000D_
for (var key in p) if (p.hasOwnProperty(key)) {_x000D_
  var value = p[key];_x000D_
  console.log(key, value);_x000D_
}
_x000D_
_x000D_
_x000D_


In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

this will give the same result as using for...in es6 loop.

for(var key in p) {
    console.log(key);
}

But its important to know the capabilities you now have using es6!


I would do this rather than checking obj.hasOwnerProperty within every for ... in loop.

var obj = {a : 1};
for(var key in obj){
    //obj.hasOwnProperty(key) is not needed.
    console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
    throw new Error("Please don't extend the native object");
}

via prototype with forEach() which should skip the prototype chain properties:

Object.prototype.each = function(f) {
    var obj = this
    Object.keys(obj).forEach( function(key) { 
        f( key , obj[key] ) 
    });
}


//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3

You can just iterate over it like:

for (var key in p) {
  alert(p[key]);
}

Note that key will not take on the value of the property, it's just an index value.


_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
_x000D_
for (var key in p) {_x000D_
    if (p.hasOwnProperty(key)) {_x000D_
        console.log(key + " = " + p[key]);_x000D_
    }_x000D_
}
_x000D_
<p>_x000D_
  Output:<br>_x000D_
  p1 = values1<br>_x000D_
  p2 = values2<br>_x000D_
  p3 = values3_x000D_
</p>
_x000D_
_x000D_
_x000D_


The question won't be complete if we don't mention about alternative methods for looping through objects.

Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.

  1. If you work with jQuery, you may use jQuery.each() method. It can be used to seamlessly iterate over both objects and arrays:

    $.each(obj, function(key, value) {
        console.log(key, value);
    });
    
  2. In Underscore.js you can find method _.each(), which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):

    _.each(obj, function(value, key) {
        console.log(key, value);
    });
    
  3. Lo-Dash provides several methods for iterating over object properties. Basic _.forEach() (or it's alias _.each()) is useful for looping through both objects and arrays, however (!) objects with length property are treated like arrays, and to avoid this behavior it is suggested to use _.forIn() and _.forOwn() methods (these also have value argument coming first):

    _.forIn(obj, function(value, key) {
        console.log(key, value);
    });
    

    _.forIn() iterates over own and inherited enumerable properties of an object, while _.forOwn() iterates only over own properties of an object (basically checking against hasOwnProperty function). For simple objects and object literals any of these methods will work fine.

Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in loop will usually be faster than any abstraction, such as jQuery.each(), these methods are considerably easier to use, require less coding and provide better error handling.


Preface:

  • Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
  • Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
  • Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.

Here in 2018, your options for looping through an object's properties are (some examples follow the list):

  1. for-in [MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
  2. Object.keys [MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
  3. Object.values [MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
  4. Object.entries [MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties (each entry in the array is a [name, value] array).
  5. Object.getOwnPropertyNames [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
  6. Object.getOwnPropertySymbols [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
  7. Reflect.ownKeys [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.
  8. If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and Object.getPrototypeOf [MDN, spec] and use Object.getOwnPropertyNames, Object.getOwnPropertySymbols, or Reflect.ownKeys on each object in the prototype chain (example at the bottom of this answer).

With all of them except for-in, you'd use some kind of looping construct on the array (for, for-of, forEach, etc.).

Examples:

for-in:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name in o) {_x000D_
    const value = o[name];_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.keys (with a for-of loop, but you can use any looping construct):

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Object.keys(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.values:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const value of Object.values(o)) {_x000D_
    console.log(`${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.entries:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const [name, value] of Object.entries(o)) {_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.getOwnPropertyNames:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Object.getOwnPropertyNames(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.getOwnPropertySymbols:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Object.getOwnPropertySymbols(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${String(name)} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Reflect.ownKeys:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Reflect.ownKeys(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${String(name)} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

All properties, including inherited non-enumerable ones:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {_x000D_
    for (const name of Reflect.ownKeys(current)) {_x000D_
        const value = o[name];_x000D_
        console.log(`[${depth}] ${String(name)} = ${String(value)}`);_x000D_
    }_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_


Since ES2015 you can use the for of loop, to access the element directly:

// before ES2015
for(var key of elements){
  console.log(elements[key]);
}


// ES2015
for(let element of elements){
  console.log(element);
}

Hope this helps someone.


If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)

_x000D_
_x000D_
for (let o of Object.getOwnPropertyNames(Math)) {_x000D_
  console.log(o);_x000D_
}
_x000D_
_x000D_
_x000D_

I sometimes use this to fast test all functions on objects with simple inputs and outputs.


Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.

Since plain JS object isn't iterable just out of box, we aren't able to use for..of loop for iterating over its content. But no one can stop us to make it iterable.

Let's we have book object.

let book = {
  title: "Amazing book",
  author: "Me",
  pages: 3
}

book[Symbol.iterator] = function(){

  let properties = Object.keys(this); // returns an array with property names
  let counter = 0;
  let isDone = false;

  let next = () => {
    if(counter >= properties.length){
      isDone = true;
    }
    return { done: isDone, value: this[properties[counter++]] }
  }

  return { next };
}

Since we've made it we can use it this way:

for(let pValue of book){
  console.log(pValue);
}
------------------------
Amazing book
Me
3

Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.

book[Symbol.iterator] = function *(){

  let properties = Object.keys(this);
  for (let p of properties){
    yield this[p];
  }

}

Sure, you can apply such behavior for all objects with making Object iterable on prototype level.

Object.prototype[Symbol.iterator] = function() {...}

Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.

let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]

Or you can use destructuring assignment:

let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3

You can check out JSFiddle with all code I've provided above.


You have to use the for-in loop

But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.

Therefore, when using for-in loops, always make use of the hasOwnProperty method to determine if the current property in iteration is really a property of the object you're checking on:

for (var prop in p) {
    if (!p.hasOwnProperty(prop)) {
        //The current property is not a direct property of p
        continue;
    }
    //Do your logic with the property here
}

since ES06 you can get the values of an object as array with

let arrValues = Object.values( yourObject) ;

it return the an array of the object values and it not extract values from Prototype!!

MDN DOCS Object.values()

and for keys ( allready answerd before me here )

let arrKeys   = Object.keys(yourObject);

In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys

More information you can see on MDN

My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

You can compare performance of this approach with different implementations on jsperf.com:

Browser support you can see on Kangax's compat table

For old browser you have simple and full polyfill

UPD:

performance comparison for all most popular cases in this question on perfjs.info:

object literal iteration


If your application is in string creation, a nice combination is with Object.keys, implode and the .map array method. For example, if we have a json object like

var data = {
    key1: 10,
    key2: 'someString',
    key3: 3000
}

.. and we'd like to generate "The values are key1 = 10, key2 = someString, key3 = 3000."

We can accomplish this in the single line of code:

var str = `The values are ${implode(', ', Object.keys(data).map(function(key){return `${key} = ${data[key]}`}))}.`;

Implode collapses an array to a string with a delimiter (first argument) inserted between elements; .map iterates through an array returning an array, and Object.keys has been elaborated quite well by the other answers.


Besause the asker's ['ultimate goal is to loop through some key value pairs'] and finally don't looking for a loop.

var p ={"p1":"value1","p2":"value2","p3":"value3"};
if('p1' in p){
  var val=p['p1'];
  ...
}

You can add a simple forEach function to all objects, so you can automatically loop through any object:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        for (var key in this) {
            if (!this.hasOwnProperty(key)) {
                // skip loop if the property is from prototype
                continue;
            }
            var value = this[key];
            func(key, value);
        }
    },
    enumerable: false
});

For those people who don't like the "for ... in"-method:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        var arr = Object.keys(this);
        for (var i = 0; i < arr.length; i++) {
            var key = arr[i];
            func(key, this[key]);
        }
    },
    enumerable: false
});

Now, you can simple call:

p.forEach (function(key, value){
    console.log ("Key: " + key);
    console.log ("Value: " + value);
});

If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.


Object.keys(obj) : Array

retrieves all string-valued keys of all enumerable own (non-inherited) properties.

So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){}) is supposed to be faster. Let's prove it:

_x000D_
_x000D_
var uniqid = function(){_x000D_
   var text = "",_x000D_
     i = 0,_x000D_
     possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";_x000D_
   for( ; i < 32; i++ ) {_x000D_
     text += possible.charAt( Math.floor( Math.random() * possible.length ) );_x000D_
   }_x000D_
   return text;_x000D_
  }, _x000D_
  CYCLES = 100000,_x000D_
  obj = {}, _x000D_
  p1,_x000D_
  p2,_x000D_
  p3,_x000D_
  key;_x000D_
_x000D_
// Populate object with random properties_x000D_
Array.apply( null, Array( CYCLES ) ).forEach(function(){_x000D_
 obj[ uniqid() ] = new Date()_x000D_
});_x000D_
_x000D_
// Approach #1_x000D_
p1 = performance.now();_x000D_
Object.keys( obj ).forEach(function( key ){_x000D_
 var waste = obj[ key ];_x000D_
});_x000D_
_x000D_
p2 = performance.now();_x000D_
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");_x000D_
_x000D_
// Approach #2_x000D_
for( key in obj ) {_x000D_
 if ( obj.hasOwnProperty( key ) ) {_x000D_
  var waste = obj[ key ];_x000D_
 }_x000D_
}_x000D_
_x000D_
p3 = performance.now();_x000D_
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
_x000D_
_x000D_
_x000D_

In my Firefox I have following results

  • Object.keys approach took 40.21101451665163 milliseconds.
  • for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.

PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa

PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:

_x000D_
_x000D_
let map = new Map().set('a', 1).set('b', 2);_x000D_
for (let pair of map) {_x000D_
    console.log(pair);_x000D_
}_x000D_
_x000D_
// OR _x000D_
let map = new Map([_x000D_
    [false, 'no'],_x000D_
    [true,  'yes'],_x000D_
]);_x000D_
map.forEach((value, key) => {_x000D_
    console.log(key, value);_x000D_
});
_x000D_
_x000D_
_x000D_


If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj) to return an array of all properties (enumerable or not) found directly upon a given object.

_x000D_
_x000D_
var obj = Object.create({}, {_x000D_
  // non-enumerable property_x000D_
  getFoo: {_x000D_
    value: function() { return this.foo; },_x000D_
    enumerable: false_x000D_
  }_x000D_
});_x000D_
_x000D_
obj.foo = 1; // enumerable property_x000D_
_x000D_
Object.getOwnPropertyNames(obj).forEach(function (name) {_x000D_
  document.write(name + ': ' + obj[name] + '<br/>');_x000D_
});
_x000D_
_x000D_
_x000D_


I had a similar problem when using Angular, here is the solution that I've found.

Step 1. Get all the object keys. using Object.keys. This method returns an array of a given object’s own enumerable properties.

Step 2. Create an empty array. This is an where all the properties are going to live, since your new ngFor loop is going to point to this array, we gotta catch them all. Step 3. Iterate throw all keys, and push each one into the array you created. Here’s how that looks like in code.

    // Evil response in a variable. Here are all my vehicles.
let evilResponse = { 
  "car" : 
    { 
       "color" : "red",
       "model" : "2013"
    },
   "motorcycle": 
    { 
       "color" : "red",
       "model" : "2016"
    },
   "bicycle": 
    { 
       "color" : "red",
       "model" : "2011"
    }
}
// Step 1. Get all the object keys.
let evilResponseProps = Object.keys(evilResponse);
// Step 2. Create an empty array.
let goodResponse = [];
// Step 3. Iterate throw all keys.
for (prop of evilResponseProps) { 
    goodResponse.push(evilResponseProps[prop]);
}

Here is a link to the original post. https://medium.com/@papaponmx/looping-over-object-properties-with-ngfor-in-angular-869cd7b2ddcc


A good way for looping on an enumerable JavaScript object which could be awesome and common for ReactJS is using Object.keys or Object.entries with using map function. like below:

// assume items:

const items = {
  first: { name: 'phone', price: 400 },
  second: { name: 'tv', price: 300 },
  third: { name: 'sofa', price: 250 },
};

For looping and show some UI on ReactJS act like below:

~~~
<div>
  {Object.entries(items).map(([key, ({ name, price })]) => (
    <div key={key}>
     <span>name: {name}</span>
     <span>price: {price}</span>
    </div>
  ))}
</div>

Actually, I use the destructuring assignment twice, once for getting key once for getting name and price.


Here is another method to iterate through an object.

_x000D_
_x000D_
   var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
_x000D_
_x000D_
Object.keys(p).forEach(key => { console.log(key, p[key]) })
_x000D_
_x000D_
_x000D_


Multiple way to iterate object in javascript

Using for...in loop

_x000D_
_x000D_
 var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
for (let key in p){_x000D_
   if(p.hasOwnProperty(key)){_x000D_
     console.log(`${key} : ${p[key]}`)_x000D_
   }_x000D_
}
_x000D_
_x000D_
_x000D_

Using for...of loop

_x000D_
_x000D_
 var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
for (let key of Object.keys(p)){_x000D_
     console.log(`key: ${key} & value: ${p[key]}`)_x000D_
}
_x000D_
_x000D_
_x000D_

Using forEach() with Object.keys, Object.values, Object.entries

_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
Object.keys(p).forEach(key=>{_x000D_
   console.log(`${key} : ${p[key]}`);_x000D_
});_x000D_
Object.values(p).forEach(value=>{_x000D_
   console.log(value);_x000D_
});_x000D_
Object.entries(p).forEach(([key,value])=>{_x000D_
    console.log(`${key}:${value}`)_x000D_
})
_x000D_
_x000D_
_x000D_


It's interesting people in these answers have touched on both Object.keys() and for...of but never combined them:

var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
    console.log(key + ':' + map[key]);

You can't just for...of an Object because it's not an iterator, and for...index or .forEach()ing the Object.keys() is ugly/inefficient.
I'm glad most people are refraining from for...in (with or without checking .hasOwnProperty()) as that's also a bit messy, so other than my answer above, I'm here to say...


You can make ordinary object associations iterate! Behaving just like Maps with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)

var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
    //key:value
    console.log(pair[0] + ':' + pair[1]);

//or
for (let [key, value] of ordinaryObject)
    console.log(key + ':' + value);

So long as you include my shim below:

//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
    var keys = Object.keys(this)[Symbol.iterator]();
    var obj = this;
    var output;
    return {next:function() {
        if (!(output = keys.next()).done)
            output.value = [output.value, obj[output.value]];
        return output;
    }};
};

Without having to create a real Map object that doesn't have the nice syntactic sugar.

var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
    console.log(pair[0] + ':' + pair[1]);

In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!

//shown in demo
var realMap = new Map({well:'hello', there:'!'});

For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;

//no prototype manipulation
function getObjIterator(obj) {
    //create a dummy object instead of adding functionality to all objects
    var iterator = new Object();

    //give it what the shim does but as its own local property
    iterator[Symbol.iterator] = function() {
        var keys = Object.keys(obj)[Symbol.iterator]();
        var output;

        return {next:function() {
            if (!(output = keys.next()).done)
                output.value = [output.value, obj[output.value]];
            return output;
        }};
    };

    return iterator;
}

Now you can just call it as an ordinary function, nothing else is affected

var realMap = new Map(getObjIterator({well:'hello', there:'!'}))

or

for (let pair of getObjIterator(ordinaryObject))

There's no reason why that wouldn't work.

Welcome to the future.


After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:

for (var key in p) {
    console.log(key + ' => ' + p[key]);
    // key is key
    // value is p[key]
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to each

jQuery animated number counter from zero to value How to iterate over array of objects in Handlebars? Excel VBA For Each Worksheet Loop jQuery looping .each() JSON key/value not working jQuery '.each' and attaching '.click' event How to use continue in jQuery each() loop? jQuery .each() with input elements C++ for each, pulling from vector elements jQuery each loop in table row Get href attribute on jQuery