WebMasterCampus
WEB DEVELOPER Resources

Javascript Object Loop Through Using for..of

Learn how to Loop Through a Javascript Object Using for..of


Javascript Loop for..of

ECMAScript 6 introduce the for…of statement that creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects, TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

The Object.keys() method returns an array of a given object’s own enumerable property names, iterated in the same order that a normal loop would.

for…of Syntax

for (variable of iterable) 
{

  statement  
} 

variable: A different property name is assigned to variable on each iteration.

object: Object whose iterable properties are iterated.

Example Of for…of

 <script>
    var p = {
        1: "value1",
        "key2": "value2",
        key3: "value3"
    };

    for (var key of Object.keys(p)) {

        (key + " -> " + p[key]);
    }
  </script>

Reference

mozilla.org

Created with love and passion.