By Tanmoy


2009-03-26 06:01:47 8 Comments

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.

30 comments

@Vahid Akhtar 2020-01-04 11:13:47

Multiple way to iterate object in javascript

Using for...in loop

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

Using for...of loop

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

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

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

@levik 2009-03-26 06:12:13

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

@Steve Midgley 2011-08-18 22:03:47

Would propose that you change the alert line just for clarity to alert(key + " -> " + JSON.stringify(p[key]));

@kamaci 2011-08-22 12:46:44

Can you explain the need for hasOwnProperty? What you mean by prototype?

@danieltalsky 2012-01-27 15:56:46

In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.

@eomeroff 2013-06-19 08:33:42

"Unfortunately, hasOwnProperty is a method, not an operator, so in any object it could be replaced with a different function or even a value that is not a function"

@Michael Bushe 2014-02-25 04:18:44

For..in is ugly, error-prone and deprecated (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…‌​). Use Object.keys() unless you have to support archeologists using IE8 or below.

@Ben Y 2014-02-27 16:08:55

Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.

@George Sovetov 2014-04-11 09:07:35

WebStorm and similar JetBrains IDEs have inspections on issue with missing hasOwnProperty.

@Alper 2014-05-27 11:59:11

I do this but my key always at least returns "undefined" even if the object is empty. Why is this?

@stanleyxu2005 2014-06-08 06:23:15

@kamaci This link stackoverflow.com/questions/135448/… explains it very detailed

@Zubair Alam 2014-08-29 19:01:50

each object in javascript (actually a key-value pair) has a property called __proto__ or prototype. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of using hasOwnProperty, which signifies that we're interested in objects own property and not its parent ones.

@Muhammad Suleman 2015-02-27 06:47:05

its not loop through null attributes .. why ?

@Michael 2015-03-04 21:13:14

Don't use obj.hasOwnProperty(prop) for membership checks. Use Object.prototype.hasOwnProperty.call(obj, prop) instead, which works even if the "set" contains the value "hasOwnProperty". Source: stackoverflow.com/questions/7958292/…

@Biber 2016-11-22 20:54:17

for...in is a good solution, but if you use promises in the for()-loop be careful, because if you create a var in the loop, you can't use it in the promise' then-function. You var in the loop exists only onr time, so it has in every then-function the same even the last value. If you have that problem, try "Object.keys(obj).forEach" or my answer below.

@TheCrazyProgrammer 2017-03-01 18:29:32

For clarity sake, you should declare the variable outside of the loop.

@Mohammed 2017-04-07 14:17:54

this is "bugging" me. Ok besides the lame joke. I am wondering why are all these methods better than just doing console.log(i + ": " + car[i]);? to show both index/key and value of array?

@Ahmad 2017-09-16 10:48:55

Not a good solution cause it would loop though all the values in proto obj and if you are some good levels deep then great performance hit. Use Object.keys() as mentioned in Axel Rauschmayer answer.

@Harsh Kanchina 2017-10-26 13:17:45

if (p.hasOwnProperty(key)) { - Here, would the key be just that,or the actual name of the key inside the object?

@Colin Keenan 2018-05-12 20:36:33

Testing in node.js, there doesn't seem to be any need for hasOwnProperty. Arrays just return all the valid indexes and objects all the valid keys. There's nothing extra to filter out.

@billynoah 2018-10-09 15:17:32

"In javascript, every object has a bunch of built-in key-value pairs that have meta-information" - not true. for instance var obj = { "a" : "123" } ; for (var k in obj) { ... } <- no problem.

@Marek Bernád 2018-10-14 12:25:34

For those as me who where looking for this: json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"‌​value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }

@Jeú Casulo 2018-11-29 01:01:08

Hi, I am using a code just like that. The problem is when I have "multiple same keys" I can't access them. Ex: obj = {'key1':'one','key2':'two','key1':'one'}, sugestions?

@Eduardo Lucio 2019-03-14 20:24:05

It will only iterate in the keys that are in the first level of the object (json). It will not interact in objects that are inside other objects. It was useful to me for that reason. =D

@bullgare 2019-03-17 18:34:33

It's so outdated. Please better consider this comment - stackoverflow.com/a/5737136/801426. Summary - use Object.entries()

@Martin Barker 2019-06-25 11:13:28

@bullgare Object.entries going into values as well.

@Alicia 2019-08-29 10:13:47

If you want to preserve the keys and values, here is a modified version: gist.github.com/Lissy93/0de24b3832caacb5e0e69b5ed6d7fc32

@Thushan 2019-09-20 10:40:52

Here you could use block scope variable (let) for the key. It would be like below for (let key in p) { }

@Nicolas Cabanas 2019-10-30 21:05:02

Using a for-of on Object.keys()

Like:

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

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

@Onera 2019-08-13 07:14:45

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

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

Object.keys(p).forEach((key)=> {
 console.log(key +' -> '+ p[key]);
});

@Swap-IOS-Android 2019-09-18 14:39:48

You saved my time, Thank you

@Onera 2019-09-26 09:52:12

Happy to know:)

@Randhir Rawatlal 2019-06-08 18:26:18

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.

@Axel Rauschmayer 2011-04-20 21:59:19

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.

@David Harkness 2014-06-23 20:36:11

Why didn't the standard provide Object.forEach(obj, function (value, key) {...})? :( Certainly obj.forEach(function...) would be shorter and complement Array.prototype.forEach, but that would risk having objects define their own forEach property. I suppose Object.keys guards against the callback modifying the object's keys.

@David Harkness 2014-06-23 20:41:48

Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }

@Andreas Linnert 2016-07-14 12:50:24

@DavidHarkness There is Object.entries in ES2017. There you can do the following: Object.entries(obj).map/forEach(([key, value]) => console.log(key, value)) ([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)

@Saravanabalagi Ramachandran 2017-01-22 15:42:17

how do I get index of the key in json? Or if required i should use a separate counter?

@Saravanabalagi Ramachandran 2017-01-22 15:45:35

i need index; syntax is forEach((element, index, array) => {}), so will forEach([k,v], index, array) work?

@Devin G Rhode 2017-05-17 03:29:32

Although Object keys fundamentally don't have an index, the array given from Object.entries of course does. Yes @ZekeDran's method works, I just tested in babel's online repl (babeljs.io/repl/…)

@Rax Weber 2017-09-06 07:45:54

for...of is ES6 standard, not ES2016.

@João Pimentel Ferreira 2018-08-13 11:39:44

why key in ES6 is const?

@João Pimentel Ferreira 2018-10-03 19:39:32

According to MDN documentation for...of is not supported by Internet Explorer.

@T.J. Crowder 2019-05-15 17:55:10

Hope you don't mind my adding the Object.entries, for-of, destructuring example. :-)

@T.J. Crowder 2018-07-10 10:39:33

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:

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

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

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

Object.values:

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

Object.entries:

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

Object.getOwnPropertyNames:

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

Object.getOwnPropertySymbols:

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

Reflect.ownKeys:

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

All properties, including inherited non-enumerable ones:

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

@serraosays 2019-04-22 04:46:17

Nice addition of enumerable/non-enumberable object properties.

@Giovanni G. PY 2019-02-07 05:28:47

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

<body>
<script>
function createTable(objectArray, fields, fieldTitles) {
  let body = document.getElementsByTagName('body')[0];
  let tbl = document.createElement('table');
  let thead = document.createElement('thead');
  let thr = document.createElement('tr');

  for (p in objectArray[0]){
    let th = document.createElement('th');
    th.appendChild(document.createTextNode(p));
    thr.appendChild(th);
    
  }
 
  thead.appendChild(thr);
  tbl.appendChild(thead);

  let tbdy = document.createElement('tbody');
  let tr = document.createElement('tr');
  objectArray.forEach((object) => {
    let n = 0;
    let tr = document.createElement('tr');
    for (p in objectArray[0]){
      var td = document.createElement('td');
      td.appendChild(document.createTextNode(object[p]));
      tr.appendChild(td);
      n++;
    };
    tbdy.appendChild(tr);    
  });
  tbl.appendChild(tbdy);
  body.appendChild(tbl)
  return tbl;
}

createTable([
              {name: 'Banana', price: '3.04'}, // k[0]
              {name: 'Orange', price: '2.56'},  // k[1]
              {name: 'Apple', price: '1.45'}
           ])
</script>

@nrb 2018-10-24 19:51:03

Object.entries() function:

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

for (var i in Object.entries(p)){
	var key = Object.entries(p)[i][0];
	var value = Object.entries(p)[i][1];
	console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}

@nrb 2018-10-29 19:22:41

please don't remove the snippet if you edit my entry

@Bryan 2009-03-26 06:05:01

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.

@Vatsal 2016-06-02 20:18:27

This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly

@billynoah 2018-10-09 15:16:16

I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.

@senthil 2018-06-26 14:34:43

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

@Marek Bernád 2018-10-14 12:27:02

json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"‌​value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }

@Ankit 2018-09-11 05:55:01

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

Object.entries(p);

@yehonatan yehezkel 2018-07-09 16:15:57

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);

@Sean Lindo 2018-08-21 19:03:43

The answers asks for a solution that returns both keys and values.

@Hashbrown 2016-06-28 09:42:22

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.

@Hashbrown 2016-07-22 06:57:17

Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!

@Janus Troelsen 2016-09-30 10:19:37

@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.

@Hashbrown 2016-09-30 12:58:44

@JanusTroelsen did you even read the whole answer? 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ɥʇʎԀʎzɐɹƆ 2018-06-14 15:17:07

Note that this technique doesn't work on plain objects, but useful nonetheless.

@Hashbrown 2018-06-15 06:47:44

it does work for plain objects, that's literally the whole point (as well as the variable names like ordinaryObject for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)

@noɥʇʎԀʎzɐɹƆ 2018-06-15 20:52:22

My fault, I didn't read the part on the shim. It doesn't work for plain objects without modifying the prototype.

@Hashbrown 2018-06-16 03:18:40

Again, @noɥʇʎԀʎzɐɹƆ, not true: DEMO. Take a look at my response to @Janus. Hmm, two people have struggled and said this now, so I'll update the answer to make it better, I mightn't have explained how to adapt the technique to not need a prototype manipulation properly

@ParaMeterz 2012-02-21 11:22:41

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

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

@Zectbumo 2018-02-26 02:42:25

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

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

for (var key in p) if (p.hasOwnProperty(key)) {
  var value = p[key];
  console.log(key, value);
}

@Matas Vaitkevicius 2018-02-07 11:22:18

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)

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

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

@Martin Barker 2019-06-25 11:17:27

I don't know why it was downvoted, but looking at this now this is perfect because in javascript "methods" are just properties on an Object in JS let test = function(){ this.method = () => {}; } console.log(new test());

@Harsh Patel 2017-12-20 04:42:57

Here is another method to iterate through an object.

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


Object.keys(p).forEach(key => { console.log(key, p[key]) })

@Rolf 2018-03-10 00:17:11

This is pretty cool, however for large objects, the for method might be more performant.

@George Bailey 2017-11-16 20:04:39

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

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

Object.keys(p).map((key)=> console.log(key + "->" + p[key]))

@Dan Alboteanu 2017-11-13 16:05:12

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

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

@Jaime Rios 2017-10-10 18:57:33

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

@FieryCod 2016-08-27 09:06:28

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:

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}`);
}

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.

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}`);
}

You can find more about usage on MDN page

@Dean Radcliffe 2017-09-28 16:36:45

This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.

@Biber 2016-11-22 20:46:31

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.

@Moritz 2017-01-06 13:06:50

Modifying the prototypes of built in objects (like Object) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.

@Lewis 2015-07-09 08:22:46

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");
}

@Bamieh 2016-09-20 09:04:34

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!

@ooo 2019-05-03 05:32:35

A custom object iterator calls the built-in array iterator of an array that generated by Object.keys() and allocated in memory... Cool!

@Pencroff 2013-11-16 19:59:49

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

@Jamie Hutber 2014-03-20 23:05:38

Indeed, I just wanted to post this method. But you beat me to it :(

@Artyom Pranovich 2016-09-01 20:15:42

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.

@Pika 2016-09-08 03:34:18

I found the code will generate the values but without keys. Is it possible to iterate the values with keys?

@Artyom Pranovich 2016-09-08 13:33:30

Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"

@Tadas V. 2016-07-22 03:48:23

If anybody needs to loop through arrayObjects with condition:

var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];

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

@Nicolas Bouvrette 2016-06-18 02:11:52

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.

@abalter 2016-06-18 06:24:27

Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211

@Nicolas Bouvrette 2016-06-18 12:56:02

@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2

@abalter 2016-06-18 16:07:52

I'm in chrome and getting Uncaught TypeError: Object.entries is not a function. Is it not implemented in chrome yet?

@Nicolas Bouvrette 2016-06-18 16:39:33

@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@abalter 2016-06-19 05:39:06

Sorry I missed that about the flag. I see it's not a fully implemented feature yet.

@Nicolas Bouvrette 2016-06-19 11:38:14

@abalter It's very early to adopt it. I'm not sure what you are trying to do but did you look at alternative solutions such as github.com/nbouvrette/forEach

@abalter 2016-06-19 21:16:04

I just usually use $.each or forEach along with hasOwnProperty.

@Tjorriemorrie 2016-07-12 14:56:47

Should mention this is also appropriate if using Babel.

@mohamed-ibrahim 2015-04-21 12:02:33

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
}

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6241377 View
  • 7792 Score
  • 93 Answer
  • Tags:   javascript arrays

43 Answered Questions

[SOLVED] Loop through an array in JavaScript

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

29 Answered Questions

[SOLVED] How to enumerate an enum

68 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

37 Answered Questions

[SOLVED] For-each over an array in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

49 Answered Questions

[SOLVED] Convert form data to JavaScript object with jQuery

4 Answered Questions

21 Answered Questions

[SOLVED] How to loop through a plain JavaScript object with the objects as members?

  • 2009-05-28 16:18:14
  • edt
  • 1606201 View
  • 1548 Score
  • 21 Answer
  • Tags:   javascript

Sponsored Content