1

I'm trying to read Tumblr posts via the JSON API.

Using their API, data is passed back like this:

var tumblr_api_read= {
 "posts":[
   "id":"1234",
   "regular-title":"This is the title of the post",
   "regular-body":"This is the body of the post"
 ]
}

I'm having trouble returning "regular-title" and "regular-body".

My JS code looks like this:

var tumblr= tumblr_api_read['posts'];
for (eachPost in tumblr)
{
 var id=posts[eachPost].id; //Works fine
 var regularTitle=posts[eachPost].regular-title; //Returns NaN
}

I am assuming it is because posts[eachPost].regular-title has the dash in it but am not able to find any documentation on how to make it work in this situation!

Thanks.

Matt
  • 7,022
  • 16
  • 53
  • 66
  • `posts` is an array; don’t use `for ... in` to loop over an array, use `for(i = 0; i < posts.length; i += 1)`. See also this question: http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays – Martijn Feb 18 '11 at 18:40

2 Answers2

5

javascript variable names can't contain special characters like - in your example. If you have a property with special characters in its name the only way to access it is with [] method you've used to access the posts object above which gives you an option to pass property name as a string.

var regularTitle = posts[eachPost]['regular-title'];
Tom Tu
  • 9,573
  • 35
  • 37
  • I figured it was something easy like that. Thanks for such a quick response. It worked perfectly. :) – Matt Feb 18 '11 at 18:38
  • It's easy to fall for this one when you are starting with javascript. Glad for being of help :) – Tom Tu Feb 18 '11 at 18:40
1

To further elaborate, you are actually referencing regular-title in dot notation, like you would if it was an object. But it is in fact an array, and that's why it wouldn't work even if the property value had no dashes as mentioned above.

tim
  • 3,823
  • 5
  • 34
  • 39