如何连接(变量+对象键名)以点表示法获取对象值 [英] how to concatenate (variable + object key names) to get the object values in dot notation

查看:29
本文介绍了如何连接(变量+对象键名)以点表示法获取对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的JSON对象:

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

如何正确进行串联?

推荐答案

只需做

myObj['question'+i]

这是因为点运算符不会按照javascript接受字符串.因此,您将不得不使用方括号,而方括号通常用于动态访问对象的属性.

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.

这篇关于如何连接(变量+对象键名)以点表示法获取对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆