简体   繁体   中英

Javascript object reference by variable

I have an object like:

var theObject = { 
    keyName1: { keyName2: value2, keyName3: value3, keyName4: value40 },
    ...,
    keyName10: { keyName2: value6, keyName3: value7, keyName4: value8 }
}

I know I can reference value7 by theObject["keyName10"]["keyName3"] or theObject.keyName10.keyName3 but what I need is to set a variable to something like the search path and somehow pass it to theObject and get value7 directly.

Something like:

var path = keyName10.keyName3;
var myValue = theObject(path);

Objects can be even further into the object inception. Right now I'm solving it by horrible looking nestled for-loops. Is there a better way I missed?

I just try to add a solution for fun. I will definitively do not use it like this, but the idea might work for your situation. I also question the efficiency of this approach.

var theObject = { 
    keyName1: { keyName2: value2, keyName3: value3, keyName4: value40 },
    ...,
    keyName10: { keyName2: value6, keyName3: value7, keyName4: value8 }
}
var path = 'keyName10/keyName3';


function getProp(theObject, path){
    var parts = path.split("/"),
    idx = parts[0],
    newParts = parts.splice(0, 1),
    newPath = newParts.join("/"),
    obj = theObject[idx];

    // add some validation and error handling in case or error on path 
    // or missing property on obj


    // I do not like the line below, would need to find a better way to see
    // if the function return something or it does some recursion
    // need to figure the right condition to see if we are at des
    if(parts.length == 1) {
        return obj;
    } else {
       return getProp(obj, newPath);
    }
}

Might help: How do I check if an object has a property in JavaScript?

Why not create a getter function...

var path = 'keyName10/keyName3'

function getTheThing(key){
    var parts = key.split("/")
    return theObject[parts[0]][parts[1]]
}

var myValue = getTheThing(path)

You could make it more general, by passing the object, and the key to the getter, allowing the path to be used to access different objects...

var path = 'keyName10/keyName3'

function getTheThing(key, obj){
    var parts = key.split("/")
    return obj[parts[0]][parts[1]]
}

var myValue = getTheThing(path,theObject)

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