简体   繁体   中英

adding element names to nested object

I have following variable like below

var test = [{…}, {…}, {…}]

I am trying to name to each element such that I can access elements by test.grade, test.name, and 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}}]

Then I want to access elements, for example, res.A.name or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM