Categories
each for-loop javascript loops

How do I loop through or enumerate a JavaScript object?

3406

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?

0

    4979

    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 (let [key, value] of Object.entries(p)) {
      console.log(`${key}: ${value}`);
    }
    

    8

    • 373

      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.

      Jan 27, 2012 at 15:56

    • 68

      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.

      – Ben Y

      Feb 27, 2014 at 16:08

    • How can I add the values that was looped? Thanks

      – ERROR 401

      Oct 25, 2021 at 12:25

    • (for..in) for objects, (for.. of) for arrays

      – mercury

      Nov 4, 2021 at 23:43


    • Thanks for simple answer. Its saved my time.

      Dec 9, 2021 at 20:16

    1301

    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.

    1

    • 26

      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.

      Jun 23, 2014 at 20:36


    369

    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
    }
    

    5

    • 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.

      Apr 6, 2011 at 9: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 5, 2011 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.

      Aug 5, 2011 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”.

      Nov 11, 2011 at 11:08

    • “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”

      – eomeroff

      Jun 19, 2013 at 8:56