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

折月煮酒 提交于 2019-12-05 16:43:17

问题


I have a nested Javascript object like

var data = { 'name':    { 'heading': 'Name', 'required': 1, 'type': 'String' },
             'profile': {
                  'age':   { 'heading': 'Age', 'required': 0, 'type': 'Number' },
                  'phone': { 'heading': 'Phone', 'required': 0, 'type': 'String'},
                  'city':  { 'heading': 'City', 'required': 0, 'type': 'String'},
                  },
             'status':  { 'heading': 'Status', 'required': 1, 'type': 'String' }
           };

Here, I can access the fields as data.profile.age.type or data.name.type. No Issues And if I have dynamic variable names, I can access as below. Again, No Problems.

f = 'profile'; data[f].age.type

But, here I have variable names like 'name', 'profile.age', 'profile.city' etc and obviously I cannot access them as f = 'profile.age'; data[f].type which will not work.

Can anyone guide me how to access them (get/set) in the most straight-forward and simple way?

Note: I tried this and it works for get.

data.get = function(p) { o = this; return eval('o.'+p); };
f = 'profile.age'; data.get(f).name;

though set does not seem to be simple enough. Please let me know, if there are better solutions for get and set as well.


回答1:


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



回答2:


You can just nest the brackets:

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



回答3:


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



回答4:


This uses the jquery.each() function to traverse down a json tree using a string variable that may or may not contain one or more "."'s. You could alternatively pass in an array and omit the .split();

pathString = something like "person.name"

jsonObj = something like {"person" : {"name":"valerie"}}.

function getGrandchild(jsonObj, pathString){
    var pathArray = pathString.split(".");
    var grandchild = jsonObj;
    $.each(pathArray, function(i, item){
        grandchild = grandchild[item];
    });
    return grandchild;
};

returns "valerie"



来源:https://stackoverflow.com/questions/4431641/javascript-access-nested-values-in-json-data-using-dynamic-variable-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!