how to concatenate (variable + object key names) to get the object values in dot notation [duplicate]

China☆狼群 提交于 2021-02-07 14:38:01

问题


Assuming I've a JSON object like this:

var myObj = {
    'question1': {
        'option1': 'foo',
        'option2': 'bar',
        'option3': 'baz'
    },
    'question2': {
        ...
    },
    'question3': {
        ...
    }
};

And since its children always has a number in its keys, I want to do a loop and concatenate the loop's index to the object keys, and get the values in the dot notation method...

So, I guess to get the values, I need to do some thing like this:

myObj.'question'+i

How can I do the concatenation right?


回答1:


Simply do

myObj['question'+i]

This is because the dot operator would not accept string with it as per javascript. So you will have to use square brackets instead which is often used to access properties of an object dynamically.



来源:https://stackoverflow.com/questions/40564197/how-to-concatenate-variable-object-key-names-to-get-the-object-values-in-dot

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