Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you get value from multidimential object when name path is stored in array of unknown length?

I’m creating a folder directory and need to allow users to navigate within it. I have a global variable that stores their location in the directory. How can I access the content within their selected folder.

This is what I what.

let location = ["2022","March","Week4"];
let content = folderInformation["2022"]["March"]["Week4"];

However, the file names "2022, March, Week4, ect" are set by the user.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I could do this.

let location = ["2022","March","Week4"];
let layer1 = location[0];
let layer2 = location[1];
let layer3 = location[2];
let content = folderInformation[layer1][layer2][layer3];

However, the user could be 2 layers deep or 15.

I tried

let layers = location.join("][");
let content = folderInformation[layers];

and

let layers = "["+location.join("][")+"]";
let content = folderInformation+layers;

with no success. What is the best option to access the content within the object?

>Solution :

A short version with reduce:

const content = location.reduce((o,l)=>o?.[l],folderinformation);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading