Javascript:使用动态变量名称访问JSON数据中的嵌套值 [英] Javascript: Access nested values in JSON data using dynamic variable names

查看:204
本文介绍了Javascript:使用动态变量名称访问JSON数据中的嵌套值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的Javascript对象,例如

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

在这里,我可以以data.profile.age.type或data.name.type访问这些字段.没有问题 如果我有动态变量名,则可以按以下方式访问.再次,没有问题.

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

但是,这里我有变量名,例如'name','profile.age','profile.city'等,显然我无法访问它们,因为f ='profile.age'; data [f] .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;

尽管set似乎还不够简单.如果还有更好的get和set解决方案,请告诉我.

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

推荐答案

除非绝对必要,否则请勿使用eval. :)至少在这种情况下,还有更好的方法-您可以将嵌套名称拆分成各个部分并对其进行迭代:

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

这篇关于Javascript:使用动态变量名称访问JSON数据中的嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆