简体   繁体   中英

Javascript - Access object node with variable as concatenated string

Is it possible to access an object node with the node path in a variable?

Consider this object:

var myObject = {
    settings: {
        some_key : 'some value'
        some_other_key : 'some value'
    }
};

And i've got this string:

var model = 'settings.some_key';

With this data, i want to get the value of myObject.settings.some_key .

If it was just a single "node" in the variable (for example settings , i could access it with myObject[model] , but i can't get that working when i need to go multiple levels into the object (first settings then some_key .


Edit: I was unclear in my initial question. What i actually want to do is write to the object, not read. I want to change the value of myObject.settings.some_key to something, not just access it, as i previously stated.

You can split the model value based on . and then reduce the split array, like this

console.log('settings.some_key'.split(".").reduce(function(result, currentKey) {
    return result[currentKey];
}, myObject));
# some value

To set the value, you can do something like this

var dataToBeSet = "some other value;"

'settings.some_key'.split(".").reduce(function(result, currentKey, index, array) {
    if (index === array.length - 1) {
        result[currentKey] = dataToBeSet;
    }
    return result[currentKey];
}, myObject);

console.log(myObject);

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