问题
I am trying to check if a certain item exists in a JS object. To do this, I need to use whatever ID is passed into my method. At the moment I'm struggling to actually use the variable's value. Here's what I'm doing:
data.entries.id
So I have my object setup as:
var data = {
"entries" : {
}
};
Therefore, the .id
part will check if a certain ID exists. If it does, I do nothing, if it doesn't, I want to add it. At the moment, by using data.entries.id, every time I simply check if 'id' exists in 'entries' which is not what I want. Let's say my variable value was 'part1' then instead of data.entries.id
I want it to look for data.entries.part1
.
So, how do I pass in the variable's value when I check for this, as opposed to the variable name.
I hope that makes sense, and I hope you can help!
回答1:
Use data.entries[id]; // Where id is a variable
This notation is to access the property using a variable
来源:https://stackoverflow.com/questions/16417864/accessing-object-properties-where-the-property-name-is-in-a-variable