简体   繁体   中英

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. 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'); . Also since the second param should be a string you need to access it via 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. 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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