最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Mar 8, 2012 at 3:58 Benjamin AllisonBenjamin Allison 2,1543 gold badges31 silver badges57 bronze badges 1
  • 1 Does this answer your question? Dynamically access object property using variable – Heretic Monkey Commented Jul 11, 2022 at 15:37
Add a ment  | 

1 Answer 1

Reset to default 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);
    });
});
发布评论

评论列表(0)

  1. 暂无评论