icekomo icekomo - 29 days ago 15
Javascript Question

Access object using dynamic object name

I have an object with some data inside. The first level of data are 2 arrays (body, cause). Each body and cause array have arrays inside of them (date, year).

totals:[{body:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]},
{cause:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]
}]


What I would like to do is access the body/cause array dynamically based on something the user has changed.

This is how I am accessing them now.

totals[isCause].body[isYear].date[filterNumber]);


My issues is body and date are hard coded in there, and I would like to have access to either body/cause date/year. I can't seem to find what these property names are stored as. I tried to set up a var and do something like this

var bodyCause = "body";


Then I tried to pass it back into my retriever statement.

totals[isCause].bodyCause[isYear].date[filterNumber]);


But that fails. So I'm just trying to figure out what that property name is stored as and if I can dynamically set it when I need to retrieve information.

Answer

Your attempt was almost correct. You can easyly use var bodyCause = "body"; and access the content dynamically. Instead of this

totals[isCause].bodyCause[isYear].date[filterNumber]); 

you should use this

totals[isCause][bodyCause][isYear].date[filterNumber]);

Should fix your problem.

Comments