4

So I'm grabbing a JSON via AJAX, but need to re-configure it. Part of that means using a string contained in a variable as the property name of a nested object.

But Javascript doesn't allow this. It treats variables as literal strings, instead of reading the value.

Here's a snippet:

var pvm.exerciseList = [];

$.get('folder_get.php', function(data){
    var theList = $.parseJSON(data);
    $.each(theList, function(parentFolder, files) {
        var fileList = [];
        $.each(files, function(url, name) {
            thisGuy.push({fileURL: url, fileName: name});
        });
        pvm.exerciseList.push({parentFolder: fileList});
    });
});

Is there anyway around this? I need to extract the string contained in "parentFolder." Right now, JS is just interpreting it literally.

Benjamin Allison
  • 2,134
  • 3
  • 30
  • 55
  • 1
    Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Heretic Monkey Jul 11 '22 at 15:37

1 Answers1

9

Use the [] syntax to resolve a variable as a property name. This might require an intermediary {}:

$.get('folder_get.php', function(data){
    var theList = $.parseJSON(data);
    $.each(theList, function(parentFolder, files) {
        var fileList = [];
        $.each(files, function(url, name) {
            thisGuy.push({fileURL: url, fileName: name});
        });

        // Make an object    
        var tmpObj = {};
        // And give it a property with the current value of parentFolder
        tmpObj[parentFolder] = fileList;
        // Then push it onto the array
        pvm.exerciseList.push(tmpObj);
    });
});
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Awesome! Thanks so much. Javascript has little "gotchas" hiding around every corner. – Benjamin Allison Mar 08 '12 at 04:12
  • 1
    @BenjaminAllison It's a very flexible and nuanced language, worth learning in detail. Not that you asked, but I recommend reading Douglas Crockfor's _JavaScript: The good parts_ to get a handle on where the language's dark alleys and bright spots lie. – Michael Berkowski Mar 08 '12 at 17:04
  • I've read it about 3 times, and will probably read it another 20 times!!! Thanks again Michael. – Benjamin Allison Mar 08 '12 at 21:29