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
Post a Comment