Accessing object properties where the property name is in a variable

别来无恙 提交于 2019-12-11 04:07:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!