0

I am calling an api which returns an object

var rain = data[i].rain;

$.get( "http://api.openweathermap.org/data/2.5/forecast?q=London,uk&mode=json&units=metric", function( data ) {
    var data = data.list;
    for(var i = 0; i < 12; i++){
        var rain = data[i].rain;
        console.log(rain)
    }
});

rain returns the following when I inspect the console:

Object {3h: 0.005}
Object {3h: 0.03}

I expected that rain.3h would have given me access to 0.005 and 0.03, but it doesn't. I get the following error message : Unexpected token ILLEGAL

Is this because it begins with a number? Can anyone advise how to access this property?

4
  • 2
    You can only use dot notation to access properties if the property name is a valid identifier. '3h' isn't, so use square bracket notation. Commented Jun 16, 2015 at 20:47
  • @RobG so you can always use the bracket notation, but the dot notation only in certain circumstances? Commented Jun 16, 2015 at 20:52
  • @PaulFitzgerald: Yes. Commented Jun 16, 2015 at 20:55
  • 1
    Related: How to access object properties containing special characters? Commented Jun 16, 2015 at 20:55

1 Answer 1

2

Yes it's because it begins with a number.

You can access that like this:

rain['3h']

When you have object properties named with numbers or simbols, use the bracket notation.

Sign up to request clarification or add additional context in comments.

3 Comments

Uncaught TypeError: Cannot read property '3h' of undefined returns this error
data[i].rain['3h'] perhaps?
yes, all good, got it. thanks, will upvote when the time allows me to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.