0

I have this code :

success(JSON.parse(xhr.responseText).items[0].snippet.title);

The problem is I can access what I want with this but I'd like to be able to do this :

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

And it doesn't work :(

It's probably nothing but I can't figure out why.

Thanks!

Victofu
  • 53
  • 2
  • 9

1 Answers1

0

For accessing object properties by string you need to use [ ] notation:

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

But that won't work for nested properties, here is the approach I would follow using Array.reduce and 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 the first iterarion pre will be response, and cur 'items' returning result.items and so on, it won't work when accesing array indexes though so you will need to add some extra logic inside the reduce function.

const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/);
// filter foo[1] capturing foo and 1, then assign them using destructuring. 
// Thanks for edit!
return ( Array.isArray(pre[cur]) ? pre[cur][position] : pre[cur]);
Isidrok
  • 2,015
  • 10
  • 15