Chris Chris - 3 months ago 16
Javascript Question

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?

Answer

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');