如果我有一个值数组:
['test1', 'test2', 'test3']
和一个json对象:
var tester = {'test1' : 'test 1 value', 'test2' : 'test 2 value' }
我如何使用数组值作为json对象的选择器。
我试过了: tester.myarray[0]
但这显然没有用。
编辑:
另外,我可能需要使用嵌套值,例如:
var myArray = ['test1', 'test2']
var tester = {'test1' : { 'test2' : 'test 1/2 value'}}
因此,在此示例中,我有一个数组,myArray
该数组实质上包含在json对象中查找值的路径。即tester.test1.test2
。
我希望基于数组能够在json对象中找到值
重要的是,路径的大小不是预先知道的,因此我认为我将需要遍历数组值以构建路径
您可以用来Array.prototype.map
从对象中获取相应的元素
var array1 = ['test1', 'test2', 'test3'],
tester = {'test1' : 'test 1 value', 'test2' : 'test 2 value' };
console.log(array1.map(function(currentKey) {
return tester[currentKey];
}));
# [ 'test 1 value', 'test 2 value', undefined ]
编辑:按照您的最新修改为,如果你想从嵌套结构中的数据,你可以做Array.prototype.reduce
这样的
console.log(myArray.reduce(function(result, current) {
return result[current];
}, tester));
# test 1/2 value
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句