使用点表示法字符串访问对象子属性 [英] Access object child properties using a dot notation string
问题描述
我暂时陷入了一个非常简单的JavaScript问题,但也许我只是错过了正确的搜索关键字!
说我们有一个对象
var r = {a:1,b:{b1:11,b2:99}};
有多种方法可以访问99:
rbb2
r ['b'] ['b2']
我想要的是能够定义一个字符串
var s =b.b2 ;
然后使用
<$ p访问99 $ p>
rs或r [s] //(当然不适用)
一种方法是为它编写一个函数,在dot上拆分字符串,也可以递归/迭代获取属性。但是有更简单/更有效的方法吗?在这里的任何一个jQuery API中有用吗?
这是我刚才写的一个天真的函数,但它适用于基本的对象属性:
function getDescendantProp(obj,desc){
var arr = desc.split(。) ;
while(arr.length&&(obj = obj [arr.shift()]));
return obj;
}
console.log(getDescendantProp(r,b.b2));
// - > 99
虽然有答案将此扩展为允许数组索引访问,但这并不是必需的您可以使用此方法使用点表示法指定数字索引:
getDescendantProp({a:[1,2,3]} , 'a2');
// - > 3
I'm temporarily stuck with what appears to be a very simple JavaScript problem, but maybe I'm just missing the right search keywords!
Say we have an object
var r = { a:1, b: {b1:11, b2: 99}};
There are several ways to access the 99:
r.b.b2
r['b']['b2']
What I want is to be able to define a string
var s = "b.b2";
and then access the 99 using
r.s or r[s] //(which of course won't work)
One way is to write a function for it that splits the string on dot and maybe recursively/iteratively gets the property. But is there any simpler/more efficient way? Anything useful in any of the jQuery APIs here?
Here's a naive function I wrote a while ago, but it works for basic object properties:
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
console.log(getDescendantProp(r, "b.b2"));
//-> 99
Although there are answers that extend this to "allow" array index access, that's not really necessary as you can just specify numerical indexes using dot notation with this method:
getDescendantProp({ a: [ 1, 2, 3 ] }, 'a.2');
//-> 3
这篇关于使用点表示法字符串访问对象子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!