如何使用动态属性访问对象

how access to Object with dynamics proprierties

本文关键字:访问 对象 属性 动态 何使用      更新时间:2023-09-26

例如,假设要让这个对象我用JSON.stringify打印:

var element={"name":"Hugo","age":20,"items":[{"id":"student__0","dog__0":"3}{"id":"student__1","dog__1":2}]};

所以我在我的jquery代码中有两个,我想构建字符串的名称:

for(var i=0,i<student_number;i++){
var label="student__"+i;
//no my code give me error and I don't know how access
//want to show that the value of "student__0"
console.log(element['items'][i].label);
}

如果您尝试使用 var label 访问该属性,您可以执行

for(var i=0,i<student_number;i++){
var label="student__"+i;
console.log(element['items'][i][label]); //note the label is in bracket notation not dot notation
}

这确实依赖于您的对象键被称为"student__0"而不是"id"。

如果您只是尝试访问 id 属性,则:

for(var i=0,i<student_number;i++){
    var label="student__"+i;
    console.log(element['items'][i].id);
}

应该足够了