1

I'm trying to use a string to target an object

Change str = "a.b.c"
To a.b.c


What I have

a = {
  b: {
    c: {
      d: 'working'
    }
  }
}

function go(o, v) {
  console.log(str[v])
}


str = "a.b.c" // reference to an object
go(str, "d")




How it's suppose to work

a = {
  b: {
    c: {
      d: 'working'
    }
  }
}

function go(o, v) {
  console.log(a.b.c[v])
}


str = "a.b.c"
go(str, "d")
Allen Marshall
  • 381
  • 2
  • 10
  • Why do you want to do this, anyways? It seams there would be no point, since you can just use Object syntax `a.b.c.d`. – StackSlave Oct 25 '17 at 00:38

3 Answers3

1

You can split your string on "." and then use reduce() function on the resulting array to iteratively drill into your object:

var a = {
      b: {
        c: {
          d: 'working'
        }
      }
    };

    function go(o, v) {
      return (o + "." + v).split(".").reduce((y,z) => y[z], this);
    }

    var result = go('a.b.c', 'd');
    console.log(result);
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
0

You want to use a library named object-path:

https://www.npmjs.com/package/object-path

This way you can access the value via:

str = "a.b.c" 
objectPath.get(a, str);
Scott
  • 3,736
  • 2
  • 26
  • 44
0

You can try using eval( ) function

https://www.w3schools.com/jsref/jsref_eval.asp

a = { b: { c: { d: 'working' } } }

function go(o, v) {
  console.log(eval(str)[v])
}

str = "a.b.c" 
go(str, "d")