作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个类似 JSON 的对象;
var data = {
Name : "test name",
Type : "test type",
VendorInfo :{
FirstName : "Vendor First Name",
LastName : "Vendor Last Name",
Address : "Vendor Address",
City : "Vendor City",
ZipCode : "Zip"
}
}
现在我想单独保留有关如何访问数据 var 中的字段的信息
var accessInfo=[
{ fieldName : "Name", actionName : "Edit" },
{ fieldName : "Type", actionName : "Edit" },
:
:etc..
]
现在在我的 javascript 中,我可以通过 for 循环遍历 accessInfo 数组,例如;
for(var i=0;i<accessInfo.length;i++){<br/>
data[accessInfo[i].fieldName] = "changed field";<br/>
}
这对于顶级字段工作正常,但我无法弄清楚如何访问层次结构中较低的字段..比如 data.VendorInfo.FirstName、data.VendorInfo.LastName 等
这有可能吗?我尝试输入“VendorInfo.FirstName”和 [VendorInfo][FirstName],但不行..
最佳答案
你只需要解析你的访问规范来遍历目标对象。您可以使用这样的函数:
function getProp(obj, propName) {
var prop;
var props = propName.split('.');
for (var i = 0; i < props.length; i++) {
prop = obj[props[i]];
if (typeof prop === 'null' || typeof prop === 'undefined') return prop;
}
return prop;
}
关于javascript - 如何在不使用 eval 或迭代的情况下使用其他地方指定的访问信息访问嵌套的 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12250506/
我是一名优秀的程序员,十分优秀!