javascript - Access object child properties using a dot notation string -


this question has answer here:

i'm temporarily stuck appears simple javascript problem, maybe i'm missing right search keywords!

say have object

var r = { a:1, b: {b1:11, b2: 99}}; 

there several ways access 99:

r.b.b2 r['b']['b2'] 

what want able define string

var s = "b.b2"; 

and access 99 using

r.s or r[s] //(which of course won't work) 

one way write function splits string on dot , maybe recursively/iteratively gets property. there simpler/more efficient way? useful in of jquery apis here?

here's naive function wrote while ago, works 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 answers extend "allow" array index access, that's not necessary can specify numerical indexes using dot notation method:

getdescendantprop({ a: [ 1, 2, 3 ] }, 'a.2'); //-> 3 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -