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:
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:
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:
After which value_accessed should equal the value at that point of the object.
Thanks in advance
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"},
}
}
}
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"
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("/"."']['")+"']")
After which value_accessed should equal the value at that point of the object.
Thanks in advance
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>
This question needs an answer!
Become an EE member today
7 DAY FREE TRIALMembers 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.
Open in new window