简体   繁体   English

如何使用方括号表示法使用多个变量来调用嵌套对象?

[英]How do I use Square Bracket Notation to use multiple variables to call nested objects?

I'm trying to create a function that will use multiple variables to select the correct nested object, and then be able to manipulate it. 我正在尝试创建一个函数,该函数将使用多个变量来选择正确的嵌套对象,然后对其进行操作。

var group1 = {
        fred: {
            debt: 5,
            income: 2
        },
        suzy: {
            debt: 3,
            income: 5
        }
    },
    group2 = {
        molly: {
            debt: 4,
            income: 4
        },
        jason: {
            debt: 6,
            income: 1
        }
    };

function debtCheck(group, name) {
    console.log(group.name.debt);         ==>Uncaught TypeError: Cannot read property 'debt' of undefined
    console.log(group[name].debt);        ==>Uncaught TypeError: Cannot read property 'debt' of undefined
    console.log([group][name].debt);      ==>Uncaught TypeError: Cannot read property 'debt' of undefined
    console.log([group[name]].debt);      ==>undefined
}

debtCheck('group1', 'fred');

The goal would be to have it display 5 in the console. 目标是使它在控制台中显示5。 If I only do one variable, it works fine. 如果我只做一个变量,它就可以正常工作。

function debtCheck(name) {
    console.log(group1[name].debt);
}

debtCheck('fred');

Hopefully I made it clear what I'm asking about. 希望我能清楚说明我的要求。 Thanks for the help! 谢谢您的帮助!

Other thoughts I've had about it: Is it that the base object can't be a variable? 我对此有其他想法:基础对象不能是变量吗? Or you can't have two variables in a row? 还是不能连续有两个变量?

You're passing the first argument as a string rather than the object. 您将第一个参数作为字符串而不是对象传递。 Try debtCheck(group1, 'fred'); 尝试debtCheck(group1, 'fred'); . Also since the second param should be a string you need to access it via group[name].debt . 同样,由于第二个参数应该是一个字符串,因此您需要通过group[name].debt访问它。

Some background material to help you regarding the first point: passing values/references to a function ; 关于第一点的一些背景材料可以帮助您: 将值/引用传递给函数 and regarding the second point: working with objects . 关于第二点: 使用对象

 var group1 = { fred: { debt: 5, income: 2 }, suzy: { debt: 3, income: 5 } }; var group2 = { molly: { debt: 4, income: 4 }, jason: { debt: 6, income: 1 } }; function debtCheck(group, name) { console.log(group[name].debt); } // debtCheck('group1', 'fred'); debtCheck(group1, 'fred'); 

Two things. 两件事情。 You have group1 put in as a string and not an object. 您将group1作为字符串而不是对象放入。 Second you can't use the dot notation when referencing objects by a specific variable name. 其次,在通过特定变量名称引用对象时,不能使用点符号。 You need to use square brackets. 您需要使用方括号。

Try: 尝试:

function debtCheck(group, name) {
    console.log(group[name].debt);
 }

debtCheck(group1, 'fred');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM