Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse through Javascript object properties

Tags:

javascript

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 ?

like image 412
Rocky Singh Avatar asked Dec 06 '10 11:12

Rocky Singh


People also ask

Can you iterate through an object JavaScript?

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.

Which method will you use to iterate the properties of an object?

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.

How do you traverse an array of objects in JavaScript?

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.


2 Answers

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';     } } 
like image 156
Christian Tellnes Avatar answered Oct 18 '22 02:10

Christian Tellnes


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.

like image 41
Alin Purcaru Avatar answered Oct 18 '22 02:10

Alin Purcaru