You can use reduce
for this - go through array of indices and dive deeper into the object:
str.split('.').reduce((a, i) => a[i], object)
Explanation:
First, str
is split into array, forming:
['item', 'id'].reduce((a, i) => a[i], object)
So You have array of indices, that You want to "visit". Now You call reduce
on it - it takes the indices one by one and calls a function on every one of them (the i
) and result of previous call (the a
) and returns a[i]
, so it "dives" one level deeper in the object. The first call has no "previous result" available yet, so it takes the object
as initial value.
So the real calls look like this:
i = 'item', a = {"item":{"id":123}} -> result a[i] is {"id":123}
i = 'id', a = {"id":123} -> result a[i] is 123