使用点符号字符串访问对象子属性 [英] Access object child properties using a dot notation string
问题描述
我暂时遇到了一个看似非常简单的 JavaScript 问题,但也许我只是缺少正确的搜索关键字!
I'm temporarily stuck with what appears to be a very simple JavaScript problem, but maybe I'm just missing the right search keywords!
假设我们有一个对象
var r = { a:1, b: {b1:11, b2: 99}};
有几种方法可以访问 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";
然后使用
r.s or r[s] //(which of course won't work)
一种方法是为它编写一个函数,在点上拆分字符串,并可能递归/迭代地获取属性.但是有没有更简单/更有效的方法?此处的任何 jQuery API 中是否有任何有用的东西?
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屋!