我将如何使用括号表示法中的单个变量访问深度值? [英] how would I go about accessing a deep value using a single variable in bracket notation?
本文介绍了我将如何使用括号表示法中的单个变量访问深度值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何执行以下操作 - 我有以下数据:
I am wondering how to do the following- I have the following data:
dta = {
"fielddata": {
"text1": "4B030C2E-3D53-4DF8-A3535EF377B45DE5",
"text2": "Unlabeled"
}
}
我可以像这样使用括号表示法访问
Which I can access using bracket notation like so
var result = dta["fielddata"]["text1"];
没问题,我可以像这样使用变量
no problem there, And I can use variables like so
var val1 = "fielddata",
val2 = "text1",
acc = dta[val1][val2];
log(acc);
再一次,太棒了-但是当我只有一个保存点符号的变量时呢?
again, terrific- but how about when I only have a single variable holding the dot notation?
比如,如果我只有
var val = "fielddata.text1",
acc = dta[val];
log(acc);
这将产生一个未定义的.关于如何解决这个问题的任何想法?
This would yield an undefined. Any thoughts on how to go about this?
非常感谢!马可
推荐答案
var val = "fielddata.text1",
acc = dta, // reference the base object
parts = val.split('.'), // split the val into an Array of individual parts
i;
// Iterate the parts, updating acc each time
for( i = 0; i < parts.length; i++ )
acc = acc[parts[i]];
这篇关于我将如何使用括号表示法中的单个变量访问深度值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文