var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
alert(propt + ': ' + obj[propt]);
}
How does the variable propt
represent the properties of the object? It's not a built-in method, or property. Then why does it come up with every property in the object?
It's just a
for...in
loop. Check out the documentation at Mozilla.The for...in loop represents each property in an object because it is just like a for loop. You defined propt in the for...in loop by doing:
A for...in loop iterates through the enumerable properties of an object. Whichever variable you define, or put in the for...in loop, changes each time it goes to the next property it iterates. The variable in the for...in loop iterates through the keys, but the value of it is the key's value. For example:
You can see how the variable differs from the variable's value. In contrast, a for...of loop does the opposite.
I hope this helps.
Here I am iterating each node and creating meaningful node names. If you notice, instanceOf Array and instanceOf Object pretty much does the same thing (in my application, i am giving different logic though)
note - I am inspired by Ondrej Svejdar's answer. But this solution has better performance and less ambiguous
To add ES2015's usage of
Reflect.ownKeys(obj)
and also iterating over the properties via an iterator.For example:
can be iterated over by
If you would like to iterate directly over the values of the keys of an object, you can define an
iterator
, just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set.JS will attempt to iterate via the default iterator property, which must be defined as
Symbol.iterator
.If you want to be able to iterate over all objects you can add it as a prototype of Object:
This would enable you to iterate over the values of an object with a for...of loop, for example:
Caution: As of writing this answer (June 2018) all other browsers, but IE, support generators and
for...of
iteration viaSymbol.iterator
jquery allows you to do this now:
I want to add to the answers above, because you might have different intentions from Javascript. A JSON object and a Javascript object are different things, and you might want to iterate through the properties of a JSON object using the solutions proposed above, and then be surprised.
Suppose that you have a JSON object like:
The wrong way to iterate through its 'properties':
You might be surprised of seeing the console logging
0
,1
, etc. when iterating through the properties ofprop1
andprop2
and ofprop3_1
. Those objects are sequences, and the indexes of a sequence are properties of that object in Javascript.A better way to recursively iterate through a JSON object properties would be to first check if that object is a sequence or not: