[英]adding element names to nested object
I have following variable like below 我有以下变量
var test = [{…}, {…}, {…}] var test = [{…},{…},{…}]
I am trying to name to each element such that I can access elements by test.grade, test.name, and test.area. 我正在尝试命名每个元素,以便可以通过test.grade,test.name和test.area访问元素。 I can think of most primitive way to add names to each index, but what is the most elegant way to do this? 我可以想到向每个索引添加名称的最原始的方法,但是最优雅的方法是什么?
var columns = //
var a= {};
var b= {};
var c= {};
for(var i =0; i< columns.length; i++){
a[columns[i]] = this.geta[i];
b[columns[i]] = this.getb[i];
c[columns[i]] = this.getc[i];
}
var test = [];
var Name0 = "name";
var Name1 = "grade";
var Name2 = "area";
test.push(a,b,c);
//test = [{name: Mike, grade: 10}}, {name: Sarah, grade:25}},{name:chris, grade:0}}]
This is how I want to format 这就是我要格式化的方式
[{A: {name: Mike, grade: 10}}, {B:{name: Sarah, grade:25}}, {C: {name:chris, grade:0}}] [{A:{name:迈克,等级:10}},{B:{name:Sarah,等级:25}},{C:{name:chris,等级:0}}]
Then I want to access elements, for example, res.A.name or res.B.grade... 然后我要访问元素,例如res.A.name或res.B.grade ...
If you want to access something by dot notation then it should be as object so 如果要通过点表示法访问某些内容,则应将其作为对象,这样
test.push({
grade:"grade",
person:"person",
area:"area"
});
Then you can access elements of test array and properties of element like this 然后,您可以像这样访问测试数组的元素和元素的属性
test[0].person;
test[0].grade;
test[0].area;
EDIT : as object 编辑 :作为对象
test={};
test['Name0']={person:"person1",grade:1,area:"..."};
test['Name1']={person:"person2",grade:1,area:"..."};
test['Name2']={person:"person3",grade:1,area:"..."};
and access as 和访问为
test.Name0.person
or whatever name you want to use it is string so use for/foreach 或您想使用的任何名称是字符串,请使用for / foreach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.