1

I have a function that I want to pass a variable that contains the path to an object's property. This path will change depending on where the function is being called from. I can't figure out how to save the path in a variable.

I need to save data.a.b.c in 'x'. I need to store the path to access 'c' in 'y' ( I assume using bracket notation)

function

y = [a.b.c]
calculate(data, y)   

calculate = function(data, y) { 
  x = data[y]
}
MrGood
  • 545
  • 5
  • 21
  • 1
    I assume you have `a.b.c` as a string? Like `y = 'a.b.c'`? If so, see this: http://stackoverflow.com/q/6491463 – gen_Eric Oct 16 '15 at 20:39
  • `function resolve(path,base){return path.reduce(function(o,k,_,__){var v=o&&o[k];return v;},base||Window);} x=resolve(path.split("."), data);` – dandavis Oct 16 '15 at 21:08

1 Answers1

0

You can't do what you'd like to do. A series of 'bracket notation' slices are pure syntax. But you can pass around functions of paths, like so, with the anonymous function passed to countInDeep:

var deep = {}
deep.a = {}
deep.a.b = {}
deep.a.b.c = {}
deep.a.b.c.count = 42

function countInDeep(func) {
  return func(deep).count
}

console.log(countInDeep(function(x) { return x.a.b.c }))
/* outputs: 42 */
Julian Fondren
  • 5,459
  • 17
  • 29