0

I have this simple JSON

{"places" : {
    "home" : {
        "1": "red"
    }
}}

I need to get 1 value depend on some variable which is my body class. Body class is changable. So this is my script:

(function(){    
    var bodyClass = $('body').attr('class');
    function getPlaceValue(){
        return $.getJSON('data.json', function(data) {
            var placeValue;
            placeValue = data.places.bodyClass.1;
            return placeValue;
        });
    }

    getPlaceValue().done(function(placeValue){
        console.log(placeValue);
    });
}).call(this);

I have respond that 1 value is undefined. What is wrong, is there a possible to do this?

Lukas
  • 7,384
  • 20
  • 72
  • 127
  • 5
    `data.places[bodyClass][1]`. Also I don't think you can `return placeValue;` from inside your callback. – gen_Eric Jan 08 '14 at 15:08
  • 2
    .getjson is non-blocking. it'll return immediately **BEFORE** the ajax call ever has a chance to even get out the door or produce any results. Your `return placeValue` will have nowhere to return TO. – Marc B Jan 08 '14 at 15:14
  • Possible duplication http://stackoverflow.com/questions/5809790/can-i-get-a-javascript-object-property-name-that-starts-with-a-number – DairyLea Jan 08 '14 at 16:13

1 Answers1

2

You define bodyClass as variable:

var bodyClass = $('body').attr('class');

... but then try to read a literal bodyClass property, which of course does not exist:

placeValue = data.places.bodyClass.1;

Additionally, you cannot use the dot syntax to access the 1 property:

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)

I suppose you meant this:

placeValue = data.places[bodyClass][1];
Álvaro González
  • 142,137
  • 41
  • 261
  • 360