1

我遇到了一个我认为很容易解决的问题,但我似乎无法在搜索中找到答案。

我有一堆我正在使用的 json 对象。现在我得到这样的信息,例如:

for(image in data.everfi_commons.images) {
    alert(data.everfi_commons.images[image]);
}

我想做的不是使用名称“everfi_commons”,而是使用我设置的javascript变量,如下所示:

current_project = $(this).attr("id");  // this value is 'everfi_commons'

然后我想你可以做 data.current_project.images[image]

但这似乎不起作用,我真的不明白为什么,任何见解都会有所帮助!

4

2 回答 2

2

尝试

current_project = $(this).attr("id"); // this value is 'everfi_commons'

然后

data[current_project].images[image]

您可以使用 JavaScript 访问对象属性[],这非常方便。

于 2013-09-29T21:22:37.520 回答
2

当然 - 只需参考您所指的密钥image

for (image in data[current_project].images) {
    /*             ^^^^^^^^^^^^^^^ 
                   This will refer to a key with the name of 
                   whatever is in the current_project variable */
    alert(data[current_project].images[image]);
}
于 2013-09-29T21:23:04.433 回答