}

JavaScript: Learn key value iteration

Created:

Introduction

Iterationg javascript object using key and values is a very useful way to iterate objects. In this tutorial we are going to explain differen ways to iterate using key, value.

Using a for..in loop

When using the for loop we need to use the hasOwnProperty before access the property of the object. In the code we caled "key" but it's actually a property what we are using.

    for (const prop in obj) {
        if( obj.hasOwnProperty(prop) ) {
            console.log("Property " + prop + " value " + obj[prop]);
        } 
    }              

hasOwnProperty is necessary because the object has additional properties inherited from the base object class. For more details why you need to call hasOwnProperty, check mozilla documentation of for..in.

If you don't require to iterate over objects own properties, check the following example:

javascript for (const prop in obj) { console.log(`obj.${prop} = ${obj[prop]}`); }

Using .each of jQuery

As an alternative to javascript vanilla you can use jQuery, but it's not recommend now. In the following example we are going to use jQuery .each:

javascript $.each(obj, function(k, v) { console.log("key: " + k + " value: " + v); });