0

I Know that there are lots of questions like this here on Stack, but none of then helped me; The problem I'm trying to solve is:

Say I have an (dynamic) object:

var car = {
        color: 'red',
        doors: 2,
        engine: {
            fuel: 'diesel',
            model: '6 inline'
        },
        driver: {
            name: {
                first: 'John',
                last: 'Meier',
            },
            age: 30
        }
    }

What I want to do is: Have a string inside a variable like var prop = "driver.name.first" and use it for example as

var driverName = getProp('driver.name.first');
var engineModel = getProp('engine.model');

function getProp(prop){
    return car[prop];
}

PS: It's a dynamic object which can even be a totally different one, so that's I can't use like var driverName = car[driver][name][first] or var driverName = car.driver.name.first

Anderson Ivan Witzke
  • 1,537
  • 1
  • 15
  • 24
  • 1
    how do you know what string to pass to the `getProp` function? and if you know the string to pass why cant you query the object directly? – Craicerjack Oct 19 '16 at 14:48
  • It does not matter if it is dynamic or not. If you know which string to pass to the function, you know how to call it directly – Weedoze Oct 19 '16 at 14:48
  • @Weedoze I don't know what the path will be because this will be called from a function... – Anderson Ivan Witzke Oct 19 '16 at 15:35
  • I've chosen to use [this](http://stackoverflow.com/a/22129960/5463835) solution from the duplicate answer because of [K.I.S.S](https://en.wikipedia.org/wiki/KISS_principle) – Anderson Ivan Witzke Nov 03 '16 at 18:04

0 Answers0