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?
As of JavaScript 1.8.5 you can use
Object.keys(obj)
to get an Array of properties defined on the object itself (the ones that return true forobj.hasOwnProperty(key)
).This is better (and more readable) than using a for-in loop.
Its supported on these browsers:
See the Mozilla Developer Network Object.keys()'s reference for futher information.
You can use Lodash. The documentation
The above answers are a bit annoying because they don't explain what you do inside the for loop after you ensure it's an object: YOU DON'T ACCESS IT DIRECTLY! You are actually only delivered the KEY that you need to apply to the OBJ:
This is all ECMA5 safe. Even works in the lame JS versions like Rhino ;)
You basically want to loop through each property in the object.
JSFiddle
If your environment supports ES2017 then I would recommend Object.entries:
As shown in Mozillas Object.entries() documentation:
Basically with Object.entries we can forgo the following extra step that is required with the older for...in loop:
Nowadays you can convert a standard JS object into an iterable object just by adding a Symbol.iterator method. Then you can use a
for of
loop and acceess its values directly or even can use a spread operator on the object too. Cool. Let's see how we can make it: