Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics (2015) The Request and Response Objects in Express Requests and the request object

Johnny Martinez
Johnny Martinez
9,849 Points

I'm unclear why posts[title] works since the posts.json is an object of objects, not an array of objects. posts.title?

...is it a string manipulation issue? I don't think I've seen an array used like this before.

1 Answer

akak
akak
29,445 Points

Hi Johnny,

Bracket notations is not only for arrays. You can access objects with dot notation as well as with bracket notation. In many cases there are interchangeable - here is some sort of comparison of pros and cons: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets

But in that case here I guess it's other thing. The bracket notation allows you to access properties by name stored in value. For example:

var obj = { "foo" : "bar"};

var lookingFor = "foo";

var contents = obj[lookingFor];

console.log(contents);
// outputs "bar"

The output will be "bar" - a property of foo. You couldn't do that with dot notation since obj.lookingFor would look for a key named lookingFor and obj[lookingFor] is, well, looking for a property of a key which name we store in a variable.

UPDATE: So to make it more this case specific. Since entires in post.json in this example have for a key full title text he takes the input from URL (for example Crossfit is Cool), assigns it to variable and then selects an object by that key.

var title = req.params.title // for example it equals "Crossfit is Cool"
var post = posts[title] // post now has properties of a key Crossfit is Cool that is title and description of it

Hope that helps ;)

Johnny Martinez
Johnny Martinez
9,849 Points

Fantastic answer and link! Thank you!