javascript - Can't use a string in an object path -


this question has answer here:

i have code :

success(json.parse(xhr.responsetext).items[0].snippet.title); 

the problem can access want i'd able :

var path = 'items[0].snippet.title'; success(json.parse(xhr.responsetext).path); 

and doesn't work :(

it's nothing can't figure out why.

thanks!

for accessing object properties string need use [ ] notation:

var foo = {bar : 2}; foo['bar']; // 2 

but won't work nested properties, here approach follow using array.reduce , es6:

let path = 'items.snippet.title'; let response = json.parse(xhr.responsetext); let result = path.split('.').reduce((pre,cur) => {     return pre[cur]; }, response); success(result); 

in first iterarion pre response, , cur 'items' returning result.items , on, won't work when accesing array indexes though need add logic inside reduce function.

const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/); // filter foo[1] capturing foo , 1, assign them using destructuring.  // edit! return ( array.isarray(pre[cur]) ? pre[cur][position] : pre[cur]); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -