0

Any way to specify object sub-indices with a variable?

Say I have a function that looks like this

function getProperty(property) {
    this.data = {
        name: "john",
        age: 35,
        occupation: {
            title: "coder",
            salary: 60000
        }
    };
    return this.data[property];
}

if I want the name I can do

getProperty("name");//john

but if i wanted, the salary, i can't do

getProperty("occupation.salary");

because that would try and fetch a property called literally "occupation.salary"

Is there some way to do something like this?

getProperty(["occupation"]["salary"]) //60000

The point is to be able to take an argument as a single variable and fetch that member of an object, without having parse the argument for a potentially arbitrary depth of sub-indices.

Can this be done?

chiliNUT
  • 18,989
  • 14
  • 66
  • 106

0 Answers0