Using string from variable as property name for JSON in Javascript?

So, I grab JSON through AJAX, but I need to re-configure it. Part of this means using the string contained in the variable as the name of the property of the nested object.

But Javascript does not allow this. It treats variables as literal strings, instead of reading the value.

Here is 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}); }); }); 

Anyway, around? I need to extract the string contained in "parentFolder". Now JS just interprets it literally.

+4
source share
1 answer

Use the syntax [] to resolve a variable as a property name. This may 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); }); }); 
+9
source

Source: https://habr.com/ru/post/1400329/


All Articles