Reputation: 2790
I have an object that's nested like the example below.
var posts = {
"post1": {
"slug": "slug1",
"title": "title1",
},
"post2": {
"slug": "slug2",
"title": "title2",
}
};
I'm trying to write a for/in loop that will allow me to iterate through this object.
var testLoop = function () {
for (var prop in posts){
post = prop;
console.log(post); // Outputs post1 and post2
console.log(post.slug); // Outputs undefined
}
}
As seen above, I can't store and later access the properties of each iterated object. Only the name of the object is stored and logged. When I run typeof, I see that it's not even an object, it's just a string.
How can I correctly store each iterated properties as objects (post1, post2 etc.) during the loop so I can access their properties using dot notation?
Upvotes: 1
Views: 68
Reputation: 15666
When you use
for (var prop in posts){ ... }
It loops over the string keys in the posts
object.
The main point here is that prop
will be a string, and not an object like your current code is expecting.
As users in the comments suggested, because prop
is the object key as a string, you need to use posts[prop]
to refer to the actual object.
Here is some updated code.
var testLoop = function () {
for (var prop in posts){
post = posts[prop]; // ** this is line that needs to be modified **
console.log(post); // Outputs post object
console.log(post.slug); // this should work now
}
}
Upvotes: 1