I want to traverse through JavaScript object's property
var obj = { a: 'value1', b: 'value2', c: 'value3', d: 'value4' }; for (var prop in obj) { prop = 'xxx'; }
But the above code is not working. Can you help me how to do so ?
Object. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
JavaScript does not offer any specific in-built function to traverse the array elements/objects. You can traverse an array simply using for loop or directly by element index. An array contains multiple elements of the same type, which can be traverse using for loop.
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'; } }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With