javascript tutorial - [Solved-5 Solutions] How to loop through or enumuerate a javascript object ? - javascript - java script - javascript array



Problem:

We have a JavaScript object like the following:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};
click below button to copy the code. By JavaScript tutorial team
  • Now we want to loop through all p elements (p1,p2,p3...) and get their keys and values. How can we do that?
  • We can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible we want to avoid using eval.

Solution 1:

We can use the for-in loop as shown by others. However, we also want to make sure that the key we get is an actual property of an object, and doesn't come from the prototype:

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    console.log(key + " -> " + p[key]);
  }
}
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Under ECMAScript 5, we 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]);
});
click below button to copy the code. By JavaScript tutorial team

ES2016 adds for...of :

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}
click below button to copy the code. By JavaScript tutorial team

ES2017 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)
);
click below button to copy the code. By JavaScript tutorial team

Both Object.keys() and Object.entries() iterate properties in the same order as a for...inloop but ignore the prototype chain. Only the object's own enumerable properties are iterated.

Solution 2:

We 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 our logic with the property here
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

We can just iterate over it like:

for (var key in p) {
  alert(p[key]);
}
click below button to copy the code. By JavaScript tutorial team

Note that key will not take on the value of the property, it's just an index value.

Solution 4:

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
click below button to copy the code. By JavaScript tutorial team

Solution 5:

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]
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - How to loop through or enumuerate a javascript object ?