Traverse through Javascript object properties

prop will reference the property name, not its value.

for (var prop in obj) {
    obj[prop] = 'xxx';
}

Construct documentation.

Also you may want to check if the property belongs to the object using hasOwnProperty. It may happen that someone adds properties to the prototype and those are also iterated by for ... in.


You should check that the property belongs to the object and not a prototype.

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        obj[prop] = 'xxx';
    }
}

Here is how it is done using the ES5 - Object.keys() :

Object.keys(obj).forEach(function(key, idx) {
   ...
}); 

http://jsfiddle.net/magiccrafter/bvwenh5d/

Mozilla's docs: link

Tags:

Javascript