1

I'm having a problem that I think is very easy to solve, but I can't seem to find an answer for it in my searches.

I have a bunch of json objects that I'm using. Right now I get at the info like so for example:

for(image in data.everfi_commons.images) {
    alert(data.everfi_commons.images[image]);
}

what I'd like to do instead is instead of having the name 'everfi_commons' I'd like to just use a javascript variable that I've set up like so:

current_project = $(this).attr("id");  // this value is 'everfi_commons'

and then I thought you could just do data.current_project.images[image]

but this doesn't seem to work and I don't really understand why, any insight would be helpful!

2 Answers 2

2

Sure - just refer to the key as you refer to image:

for (image in data[current_project].images) {
    /*             ^^^^^^^^^^^^^^^ 
                   This will refer to a key with the name of 
                   whatever is in the current_project variable */
    alert(data[current_project].images[image]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

it's interesting, when I do this, it goes through the alerts listing the images one at a time...but it does it twice, so goes all the way through, one, two, three, four, and then does it again, one, two, three, four
@loriensleafs Can you post your data object?
2

Try

current_project = $(this).attr("id"); // this value is 'everfi_commons'

then

data[current_project].images[image]

You can access object properties using [] in JavaScript, which is very handy.

3 Comments

Basically (just to give a small extra explanation for @loriensleaf): x.abc is the same as writing x['abc'] in javascript. Meaning that if you have a variable containing the string abc (named name), x[name] would be another way to write the same.
thanks, that's super helpful to know. Just out of curiosity, can you not write this in dot notation with the variable?
Well, to be honest, yes you can. I suggested the [] approach as a sanity check, to make sure the property does exist. But hey, at least I've shown something new :)

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.