[JS]: List of indexes as path to recursive array/object
Vandesm14 (528)

I have an array which looks something like this:

[
	[
		'setA1',
		'setA2'
	],
	[
		'setB1',
		'setB2'
	]
]

(note that this is hugely over-simplified)

If I have an path to setB1 like this "1/0", how would I implement a function to recursively move down the array and return the result?
This function should also work with an object search: "key/keyA/otherkey"
Yes, I know the path is a string. For this example you can assume it has already been split by "/", making it an array of indexes

Concept of execution:

let path = '1/3/6/0/0'; // Another example
/* function turns path to obj[1][3][6][0][0] and returns result */

Thanks in advance!

You are viewing a single comment. View All
Answered by pyelias (676) [earned 5 cycles]
View Answer
TheDrone7 (550)

Ok, so you have the array of indices. Now your function can take two parameters.
1. The object from which it needs to extract data.
2. The array of indices.

If the length of array of indices is greater than 0, use the shift method to get the first member of array of indices and also removing it from the array. Then call the function like func(l[x], i); considering, l is the object from which you need to get the value, i is the array of indices, x is the value you recieved after using the shift method.
If the length of array is not greater than 0, return the object.

Please mark this as the correct answer if this helps.