Javascript: Access nested values in JSON data using dynamic variable names

Perhaps a function that takes in the path to the property you're interested in and breaks it up into tokens representing properties. Something like this (this is very rough, of course):

data.get = function(path) {
  var tokens = path.split('.'), val = this[tokens[0]];
  if (tokens.length < 2) return val;
  for(var i = 1; i < tokens.length; i++) {
     val = val[tokens[i]];
  }
  return val;
}

example:

   var f = 'one.two';
   var data = { one: {two:'hello'}};
   data.get = /* same as above */;

   var val = data.get(f);

Don't use eval unless absolutely necessary. :) At least in this case, there are better ways to do it -- you can split the nested name into individual parts and iterate over them:

data.get = function(p) {
  var obj = this;

  p = p.split('.');
  for (var i = 0, len = p.length; i < len - 1; i++)
    obj = obj[p[i]];

  return obj[p[len - 1]];
};

data.set = function(p, value) {
  var obj = this;

  p = p.split('.');
  for (var i = 0, len = p.length; i < len - 1; i++)
    obj = obj[p[i]];

  obj[p[len - 1]] = value;
};

A clean way to access/set nested values is using reduce in ES6:

const x = ['a', 'b', 'c'], o = {a: {b: {c: 'tigerking'}}}

// Get value: "tigerking"
console.log(x.reduce((a, b) => a[b], o)) 

// Set value: 
x.slice(0, x.length-1).reduce((a, b) => a[b], o)[x[x.length-1]] = 'blossom'

console.log(o) // {a: {b: {c: 'blossom'}}}

So, you can first convert your variable 'profile.age' to an array using 'profile.age'.split('.'), then use the approach above.


You can just nest the brackets:

var a = 'name', b = 'heading';
data[a][b]; // = `Name`