Link to home
Start Free TrialLog in
Avatar of Anthony Haffey
Anthony Haffey

asked on

Robust way of using string/array to index object

Hi, my first question on Experts-Exchange.
I'm managing files in dropbox with javascript using their API. I've created an object that reflects the file structure:

file_structure = {
    folder1:{
       files:{},
       folder2:{
          files:{"hello.html":"www.this_dbx_location.org"},
       }
   }
}
 

Open in new window


I want a dynamic solution to access a variable within this structure when I have the location in the form of a string or array. For example, would it be possible to use:

var string_index = "folder1/folder2/files/hello.html"

Open in new window


To index that point of the object. Ideally, I'd like this method to allow me to have the ability to both refer to the value, and/or edit it if possible. I appreciate though that it may be necessary to have separate methods to access the value using the string vs. changing the value at the location within the object. The closest thing I've got so far is using eval, which would look like:

eval("var value_accessed = file_structure['"+string_index.replace("/"."']['")+"']")

Open in new window


After which value_accessed should equal the value at that point of the object.

Thanks in advance
Avatar of leakim971
leakim971
Flag of Guadeloupe image

var string_index = "folder1/folder2/files/hello.html"
var arrPath  = string_index.split("/"); 
var value_accessed = arrPath.pop(); // value_accessed = "hello.html"
for(var i=0;i<arrPath.length;i++) {
     // maybe you want to do something with each part of the path : "folder1", "folder2" and last(third) iteration "files"
}

Open in new window

This code will return the last matching item found in the path
<script>
var file_structure = {
    folder1:{
       files:{},
       folder2:{
          files:{"hello.html":"www.this_dbx_location.org"},
       }
   }
}
var string_index = "folder1/folder2/files/hello.html"
var val = getValue(file_structure, string_index);
console.log(val);

function getValue(data, path) {
  var parts = path.split("/");
  var last = data;
  for(var i = 0; i < parts.length; i++) {
    var current = parts[i];
    if (!last[current]) break;
    last = last[current];
  }
  return last;
}
</script>

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.