在Javascript中使用变量的字符串作为JSON的属性名称? [英] Using string from variable as property name for JSON in Javascript?
问题描述
所以我通过AJAX抓取JSON,但需要重新配置它。部分原因是使用变量中包含的字符串作为嵌套对象的属性名称。
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.
但是Javascript不允许这样做。它将变量视为文字字符串,而不是读取值。
But Javascript doesn't allow this. It treats variables as literal strings, instead of reading the value.
这是一个片段:
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});
});
});
无论如何都有这个吗?我需要提取parentFolder中包含的字符串。现在,JS只是按字面解释它。
Is there anyway around this? I need to extract the string contained in "parentFolder." Right now, JS is just interpreting it literally.
推荐答案
使用 []
将变量解析为属性名称的语法。这可能需要中间人 {}
:
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);
});
});
这篇关于在Javascript中使用变量的字符串作为JSON的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!