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

前端 未结 1 1608
栀梦
栀梦 2020-12-17 04:47

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

1条回答
  •  囚心锁ツ
    2020-12-17 05:17

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

    0 讨论(0)
提交回复
热议问题