3553

I have a JavaScript object like the following:

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

How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Tanmoy
  • 44,392
  • 16
  • 45
  • 55

48 Answers48

5140

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(`${key}: ${value}`);
}
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
levik
  • 114,835
  • 27
  • 73
  • 90
  • 378
    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. – danieltalsky Jan 27 '12 at 15:56
  • 68
    Actually, [For...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) is not deprecated. [For each...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in) is. But I really like the term _archaeologists_...I'm going to have to start using that. – Ben Y Feb 27 '14 at 16:08
  • How can I add the values that was looped? Thanks – ERROR 401 Oct 25 '21 at 12:25
  • (for..in) for objects, (for.. of) for arrays – mercury Nov 04 '21 at 23:43
  • is it possible to even do this using while loops? like while(let x in objectA || objectA[x].hasOwnProperty("childPointer") – Irvan Hilmi Apr 29 '22 at 17:58
  • I rember the diff between `of` and `in` in `for` loops with: Better to use `of`,but more practical is `in` because of no need for `Object.entries()`. Is `hasOwnProperty` also recommended in `for..of`? – Timo May 29 '22 at 08:55
  • 1
    for anyone concerned about performance, `for..in` + `hasOwnProperty` is marginally faster in normal use (https://jsben.ch/pCDAk), with `Object.keys` being significantly faster beyond a few thousand properties (https://jsben.ch/ptzsL). – jason. Nov 01 '22 at 13:10
1364

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Axel Rauschmayer
  • 25,381
  • 5
  • 24
  • 17
  • 29
    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 Jun 23 '14 at 20:36
  • 2
    Python is so easy, javascript I have to look up basics every time. – run_the_race Aug 23 '22 at 12:32
376

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
}
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • 31
    This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous. – SystemicPlural Apr 06 '11 at 09:55
  • 55
    I would not remove the `{ }` personally because an `if` without them makes it a little unclear what is part of the `if` and what is not. But I guess that's just a matter of opinion :) – pimvdb Aug 05 '11 at 12:01
  • 36
    Yes, I prefer keeping the `{ }` mainly to avoid confusion if one later on needs to add something to the `if` scope. – Andreas Grech Aug 05 '11 at 12:21
  • 8
    Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block". – Andreas Grech Nov 11 '11 at 11:08
266

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
VisioN
  • 143,310
  • 32
  • 282
  • 281
71

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;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
63

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.

Bryan
  • 3,453
  • 6
  • 26
  • 20
  • 15
    This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly – Vatsal Jun 02 '16 at 20:18
  • 4
    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. – But those new buttons though.. Oct 09 '18 at 15:16
58

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

Pencroff
  • 1,009
  • 9
  • 13
48

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

function A(obj,s='') {
 for (let key in obj) if (obj.hasOwnProperty(key)) s+=key+'->'+obj[key] + ' ';
  return s;
}

function B(obj,s='') {
 for (let key in obj) s+=key+'->'+obj[key] + ' ';
  return s;
}

function C(obj,s='') {
  const map = new Map(Object.entries(obj));
 for (let [key,value] of map) s+=key+'->'+value + ' ';
  return s;
}

function D(obj,s='') {
  let o = { 
    ...obj,
    *[Symbol.iterator]() {
      for (const i of Object.keys(this)) yield [i, this[i]];    
    }
  }
  for (let [key,value] of o) s+=key+'->'+value + ' ';
  return s;
}

function E(obj,s='') {
  let o = { 
    ...obj,
    *[Symbol.iterator]() {yield *Object.keys(this)}
  }
  for (let key of o) s+=key+'->'+o[key] + ' ';
  return s;
}

function F(obj,s='') {
 for (let key of Object.keys(obj)) s+=key+'->'+obj[key]+' ';
  return s;
}

function G(obj,s='') {
 for (let [key, value] of Object.entries(obj)) s+=key+'->'+value+' ';
  return s;
}

function H(obj,s='') {
 for (let key of Object.getOwnPropertyNames(obj)) s+=key+'->'+obj[key]+' ';
  return s;
}

function I(obj,s='') {
 for (const key of Reflect.ownKeys(obj)) s+=key+'->'+obj[key]+' ';
  return s;
}

function J(obj,s='') {
  let keys = Object.keys(obj);
 for(let i = 0; i < keys.length; i++){
    let key = keys[i];
    s+=key+'->'+obj[key]+' ';
  }
  return s;
}

function K(obj,s='') {
  var keys = Object.keys(obj), len = keys.length, i = 0;
  while (i < len) {
    let key = keys[i];
    s+=key+'->'+obj[key]+' ';
    i += 1;
  }
  return s;
}

function L(obj,s='') {
  Object.keys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );
  return s;
}

function M(obj,s='') {
  Object.entries(obj).forEach(([key, value]) => s+=key+'->'+value+' ');
  return s;
}

function N(obj,s='') {
  Object.getOwnPropertyNames(obj).forEach(key => s+=key+'->'+obj[key]+' ');
  return s;
}

function O(obj,s='') {
  Reflect.ownKeys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );
  return s;
}



// TEST

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};
let log = (name,f) => console.log(`${name} ${f(p)}`)

log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
log('O',O);
This snippet only presents choosen solutions

And here are result for small objects on chrome

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
38
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.

Kristian
  • 21,204
  • 19
  • 101
  • 176
Richard Levasseur
  • 14,562
  • 6
  • 50
  • 63
  • 4
    When using a for loop like that, `key` will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key]. – Bryan Mar 26 '09 at 06:07
  • 1
    It is the slowest method of array iteration in JavaScript. You can check this on your computer - [Best way to iterate over Arrays in JavaScript](http://jsperf.com/testing-foreach-vs-for-loop/11) – Pencroff Dec 05 '13 at 12:15
  • 7
    @Pencroff: the problem is that the question is not about looping through arrays... ;) – Sk8erPeter Jan 01 '14 at 00:55
  • This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryan `var p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }` is popping "p1" and "p2" in alerts, so whats wrong about that??? – Sebastian Aug 05 '14 at 06:43
  • 5
    I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers _are_ better than mine :). – Richard Levasseur Aug 06 '14 at 16:41
37

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

Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
FieryCod
  • 1,674
  • 1
  • 19
  • 27
  • 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. – Dean Radcliffe Sep 28 '17 at 16:36
26

Single line and more readable code can be..

Object.entries(myObject).map(([key, value]) => console.log(key, value))
Akhil Ramani
  • 391
  • 4
  • 6
  • good answer and it's more readable than the above solutions but can you explain what happens on the .map(([key, value]) in your answer? – Nivethan May 03 '22 at 13:47
  • 1
    @Nivethan the output of Object.entries will be an Array of Arrays. i.e [ ['key1', 'value'], ['key2', 'value'] ] So, map will loop over outer array with each array elements passing into its callback function one by one. So, here I have used Array de-structuring syntax ([key, value]) => {} instead of (element) => {}, where element is an array. – Akhil Ramani May 06 '22 at 02:48
23

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]
}
Francis Lewis
  • 8,872
  • 9
  • 55
  • 65
  • 18
    Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property on `Object.prototype`, then it will be enumerated by `for..in`. If you are sure you are not using any libraries that do that, then you don't need to call `hasOwnProperty`. – G-Wiz Jan 13 '12 at 20:15
  • 4
    It can be completely clean if created with `Object.create(null)` – Ruan Mendes Apr 14 '16 at 11:37
21

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
strider
  • 5,674
  • 4
  • 24
  • 29
  • 2
    Be careful with the prototype: `obj = { print: 1, each: 2, word: 3 }` produces `TypeError: number is not a function`. Using `forEach` to match the similar `Array` function may reduce the risk somewhat. – David Harkness Jun 23 '14 at 21:40
19

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
  • 12,091
  • 8
  • 72
  • 95
  • 2
    [Case](http://stackoverflow.com/a/19110204/2518317) [in](http://stackoverflow.com/a/19106881/2518317) [point](http://stackoverflow.com/a/21821236/2518317). 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! – Hashbrown Jul 22 '16 at 06:57
  • @HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself. – Janus Troelsen Sep 30 '16 at 10:19
  • @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;` – Hashbrown Sep 30 '16 at 12:58
  • Note that this technique doesn't work on plain objects, but useful nonetheless. – noɥʇʎԀʎzɐɹƆ Jun 14 '18 at 15:17
  • 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) – Hashbrown Jun 15 '18 at 06:47
  • My fault, I didn't read the part on the shim. It doesn't work for plain objects without modifying the prototype. – noɥʇʎԀʎzɐɹƆ Jun 15 '18 at 20:52
  • Again, @noɥʇʎԀʎzɐɹƆ, not true: [DEMO](https://jsfiddle.net/4dkos9mw/16/). 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 – Hashbrown Jun 16 '18 at 03:18
19

Using a for-of on Object.keys()

Like:

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

for (let key of Object.keys(object)) {
  console.log(key + " : " + object[key])
}
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
Nicolas Cabanas
  • 203
  • 2
  • 4
18

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]);
});
Onera
  • 687
  • 3
  • 14
  • 34
17

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>
TessavWalstijn
  • 1,698
  • 1
  • 19
  • 36
ParaMeterz
  • 9,507
  • 1
  • 19
  • 21
14

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:

var uniqid = function(){
   var text = "",
     i = 0,
     possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   for( ; i < 32; i++ ) {
     text += possible.charAt( Math.floor( Math.random() * possible.length ) );
   }
   return text;
  }, 
  CYCLES = 100000,
  obj = {}, 
  p1,
  p2,
  p3,
  key;

// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
 obj[ uniqid() ] = new Date()
});

// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
 var waste = obj[ key ];
});

p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");

// Approach #2
for( key in obj ) {
 if ( obj.hasOwnProperty( key ) ) {
  var waste = obj[ key ];
 }
}

p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");

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:

let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
    console.log(pair);
}

// OR 
let map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);
map.forEach((value, key) => {
    console.log(key, value);
});
Dmitry Sheiko
  • 2,130
  • 1
  • 25
  • 28
  • if you don't feel like letting go of the {} notation, you can still use `of` [without creating `Map`s](http://stackoverflow.com/a/38072602/2518317) – Hashbrown Jun 28 '16 at 09:47
14

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

let p = {foo: "bar"};
for (let [key, value] of Object.entries(p)) {
  console.log(key, value);
}
Flimm
  • 136,138
  • 45
  • 251
  • 267
Ankit
  • 960
  • 6
  • 12
13

Pass your object to Object.keys(). This will return an array containing all the keys in the object. You can then loop through the array using map. Using obj[key] where obj is your object and key is the current value in the map iteration, you can get the value for that key/property.

const obj = { name: "Jane", age: 50 };

Object.keys(obj).map( key => {
    console.log(key, obj[key]);
});
Isaac Jandalala
  • 308
  • 3
  • 9
12

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
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51
11

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]))
Muhammad Usman
  • 10,039
  • 22
  • 39
11

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]) })
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
  • 3
    This is pretty cool, however for large objects, the `for` method might be more performant. – Rolf Mar 10 '18 at 00:17
10

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}`)
})
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
8

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.

Nicolas Bouvrette
  • 4,295
  • 1
  • 39
  • 53
  • Could you provide a fiddle of this working? Here is my attempt. https://jsfiddle.net/abalter/sceeb211/ – abalter Jun 18 '16 at 06:24
  • @abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: https://jsfiddle.net/sceeb211/2/ – Nicolas Bouvrette Jun 18 '16 at 12:56
  • I'm in chrome and getting `Uncaught TypeError: Object.entries is not a function`. Is it not implemented in chrome yet? – abalter Jun 18 '16 at 16:07
  • @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: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries – Nicolas Bouvrette Jun 18 '16 at 16:39
  • Sorry I missed that about the flag. I see it's not a fully implemented feature yet. – abalter Jun 19 '16 at 05:39
  • @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 https://github.com/nbouvrette/forEach – Nicolas Bouvrette Jun 19 '16 at 11:38
  • I just usually use `$.each` or `forEach` along with `hasOwnProperty`. – abalter Jun 19 '16 at 21:16
  • Should mention this is also appropriate if using Babel. – Tjorriemorrie Jul 12 '16 at 14:56
8

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.

Biber
  • 709
  • 6
  • 19
  • 3
    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. – Moritz Jan 06 '17 at 13:06
8
Object.entries(myObject).map(([key, value]) => console.log(key, value))

You can try like this. myObject will be {name: "", phone: ""} so and so, this will generate key and value. So key here is name, phone and value are like dog, 123123.

Example {name: "dog"}

Here key is name and value is dog.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
lodey
  • 174
  • 2
  • 8
  • Hi, Welcome to Stackoverflow! As explained in the tour, this site is a repository of useful questions and their answers. Your answer is not essentially different from the other answers and not very useful since it does not add any new value or information. Please avoid writing duplicate answers, either edit your answer to add value or delete it altogether, this will ensure all questions and answers on the site remain useful not scattered/duplicated. – Maximilian Peters Feb 09 '22 at 07:50
7

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.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
  • I was exactly looking for this as I'm working with React and how for loops don't work inside ``, this is the perfect solution. Thanks a lot – Mob_Abominator Aug 19 '20 at 05:52
  • Dear @Mob_Abominator, thanks for your sweet comment, I'm glad to hear it is useful for you. but I don't understand `how for loops don't work inside `. Does it still remain any problem? if it does please leave a question and tell me, I will answer. if nothing remains and you are ok now. please leave upvote to [this post of me](https://stackoverflow.com/a/60470549/6877799). thanks. – AmerllicA Aug 19 '20 at 07:32
6

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");
}
Lewis
  • 14,132
  • 12
  • 66
  • 87
6

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!

Bamieh
  • 10,358
  • 4
  • 31
  • 52
  • 1
    A custom object iterator calls the built-in array iterator of an array that generated by `Object.keys()` and allocated in memory... Cool! – ooo May 03 '19 at 05:32
6

    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]);
        }
    }
}
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
senthil
  • 324
  • 2
  • 15
  • `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]); } } }` – Marek Bernád Oct 14 '18 at 12:27
6

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);
yehonatan yehezkel
  • 1,116
  • 18
  • 28
6
  1. Using for...in and Object hasOwnProperty

        var p = {
            "p1": "value1",
            "p2": "value2",
            "p3": "value3"
        };
    
        for (var key in p) {
            if (p.hasOwnProperty(key)) {
                console.log(key, ' : ', p[key]);
            }
        }
  2. Using for...of and Object keys

        var p = {
          "p1": "value1",
          "p2": "value2",
          "p3": "value3"
        };
    
        for (var key of Object.keys(p)) {
          console.log(key, " : ", p[key])
        }
  3. Using Object keys and forEach

        var p = {
            "p1": "value1",
            "p2": "value2",
            "p3": "value3"
        };
    
        Object.keys(p).forEach(function(key) {
            console.log(key, ' : ', p[key]);
        });
  4. Using for...of and Object entries

        var p = {
            "p1": "value1",
            "p2": "value2",
            "p3": "value3"
        };
    
        for (let [key, value] of Object.entries(p)) {
          console.log(key, ' : ', value);
        }
  5. Using Object entries and forEach

        var p = {
            "p1": "value1",
            "p2": "value2",
            "p3": "value3"
        };
    
        Object.entries(p).forEach(([key, value]) => console.log(key, ' : ', value));
Sahil Thummar
  • 1,926
  • 16
  • 16
5

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.

var obj = Object.create({}, {
  // non-enumerable property
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});

obj.foo = 1; // enumerable property

Object.getOwnPropertyNames(obj).forEach(function (name) {
  document.write(name + ': ' + obj[name] + '<br/>');
});
Dheeraj Vepakomma
  • 26,870
  • 17
  • 81
  • 104
  • 2
    This is fantastic, thank you for posting this answer. I needed to introspect an `Error` object and couldn't get at the properties in a loop or a `_.forIn(err)` call. Using `Object.getOwnPropertyNames(err)` allowed me to access all the parts of the `Error` that I couldn't get at before. Thanks! – Pierce Mar 11 '16 at 19:49
5

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");
      }
   }
}
Tadas V.
  • 775
  • 1
  • 11
  • 22
5

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.

Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60
  • I found the code will generate the values but without keys. Is it possible to iterate the values with keys? – Pika Sep 08 '16 at 03:34
  • 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 {}) { }" – Artyom Pranovich Sep 08 '16 at 13:33
5

There are a couple of options:

  1. You can use for..in for that

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

for (const item in p) {
  console.log(`key = ${item}, value = ${p[item]}`);
}
  1. You can also call Object.entries() to create an array with all its enumerable properties. after that you can and loop through it using map, foreach or for..of

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


Object.entries(p).map(item => {
  console.log(item)
})

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


Object.entries(p).forEach(item => {
  console.log(item)
})

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


for (const item of Object.entries(p)) {
  console.log(item)
}

More about Object.entries()can be found here

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
4

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
  • 312
  • 2
  • 5
3

The nearest solution, close to python's enumerate function:

for key, value in enumerate(object):
    # Do something

is a combo of Object.entries() and for-of loop:

for(let [key, value] of Object.entries(object)) {
    // Do something
}

let object = {
  key1: "value1",
  key2: "value2",
  key3: "value3",
  key4: "value4",
  key5: "value5"
};

for(let [key, value] of Object.entries(object)) {
  console.log(`${key} -> ${value}`);
}
Zayaan
  • 169
  • 1
  • 8
2

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

Jaime Rios
  • 1,956
  • 2
  • 15
  • 20
2

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>
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34
2

You may use my library monadic-objects for that. It's designed to simplify object modificatons and make it behave like arrays:

p.forEach((key, value) => console.log(key, value))

Installation: npm i monadic-objects

This library also includes methods:

  • map
  • filter
  • every
  • some

See README for more information!

cigien
  • 57,834
  • 11
  • 73
  • 112
kerelape
  • 114
  • 8
0

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
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
0

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.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
  • 1
    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());` – Barkermn01 Jun 25 '19 at 11:17
0

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

var myMap = new Map( Object.entries(p) );

for ( let [k, v] of myMap.entries() ) {

  console.log( `${k}: ${v}` )
  
}
<h3>ECMAScript 2017</h3>
<p><b>Object.entries()</b> makes it simple to convert <b>Object to Map</b>:</p>
antelove
  • 3,216
  • 26
  • 20
-1
  • 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);
}
Zectbumo
  • 4,128
  • 1
  • 31
  • 26
-3

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.

  • 2
    Not just does it not help, it's not accurate. *For...of* only works if *elements* defines an iterator. That's true of Arrays, Sets, and Maps, but not of Objects. – Evan Carroll Jun 08 '16 at 17:29
  • [you can actually make this work](http://stackoverflow.com/a/38072602/2518317), @EvanCarroll – Hashbrown Jun 28 '16 at 09:43
-6

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'];
  ...
}
B.F.
  • 477
  • 6
  • 9
  • 3
    No! He wrote "Now I want to loop through all p elements" so he realy need a loop like in his accepted answer. – Sebastian Aug 05 '14 at 06:40