views:

34

answers:

5

I have a code which has a character that JS is not handling properly.

$(document).ready(function(){


    $.getJSON("http://sjama.tumblr.com/api/read/json?callback=?",
        function (data){
            for (var i=0; i<data.posts.length; i++){

                    var blog = data.posts[i];

                    var id = blog.id;
                    var type = blog.type;

                    var photo = blog.photo-url-250;

                    if (type == "photo"){

                        $("#blog_holder").append('<div class="blog_item_holder"><div class="blog_item_top"><img src='+photo+'/></div><div class="blog_item_bottom">caption will go here</div></div>');
                    }

            }

        }); <!-- end $.getJSON

});

The problem is with this line:

   var photo = blog.photo-url-250;

after "blog." it reads the "url" part weirdly because of the dash (-) in between.

What can I do to sort this problem out?

+1  A: 

You need to access the property in square brackets with a string literal.

blog["photo-url-250"];

Likewise, when creating an object property with invalid name characters (such as the hyphen), you will use a string literal.

var blog = {
               someProperty: "someValue",     // Name has valid characters.
               "some-property": "some-value"  // This name requires a string literal.
           }

Valid characters are letters, numbers, underscore and $.

patrick dw
thanks man. it worked!
Jimmy Farax
Glad it worked. :o)
patrick dw
+1  A: 

use this instead

var photo = blog['photo-url-250'];

Read this ( http://javascript.about.com/od/variablesandoperators/a/vop04.htm ) for rules that apply to variable naming..

Your code could be read as set photo to blog.photo minus url minus 250

var photo = blog.photo - url - 250;
Gaby
+1  A: 

can you write it as blog["photo-url-250"]

sushil bharwani
+1  A: 

That's a property that should be wrapped in [] eg:

var photo = blog["photo-url-250"];
Sarfraz
+1  A: 

use other notation:

var photo = blog['photo-url-250'];
MichalBE