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

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


You can just nest the brackets:

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


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;};


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);