简体   繁体   中英

javascript object index keys

I'm trying to figure out the best way to structure my javascript object. What I would like to have is an object where I can select nested objects via keys in a similar structure to this:

        trackObject:
            [{
            row1:{rowId:"#row1",rowSample:
                {sampleId:"#1",notes:
                    [0,400,800]
                }
            },
            row2:{rowId:"#row2",rowSample:
                {sampleId:"#2",notes:
                    [0,400,800]
                }
            },                
        }]

Ideally, I would like to be able to modify this object by indexing at the 'row' tier ie row1 or row2 . The problem is making the row name a variable. Ie the object above will return me the object I need by calling trackObject.row1 but since the row1 part needs to be dynamic i'm not sure how to index it from this point dynamically.

I've tried a few variations like not making trackObject an array but an object instead and changing row1 to "row1":{rowId... but then I havn't been able to reference the object property that it nests ( {rowId... )

I've setup objects with keys in JSON before and it's been fine indexing by key but for some reason i'm struggling in js...

You can access a member of an object by using bracket notation.

var obj = {
  row1: {
    rowId: '#row1'
  },
  row2: {
    rowId: '#row2'
  }
};

// index stored in variable
var index = 'row1';

// get row by using bracket notation
var row = obj[index];

console.log(row.rowId); // '#row1';

The convenient way to structure your javascript object.
Consider using custom getter method which accepts row index/number as a parameter:

 var data = { trackObject : { row1: { rowId: "#row1", rowSample: { sampleId: "#1", notes: [0,400,800] } }, row2: { rowId: "#row2", rowSample: { sampleId: "#2", notes: [0,400,800] } }, }, getRow : function (idx) { var obj = this.trackObject['row' + idx]; if (!obj) { throw new Error("Undefined trackObject key: row" + idx); } return obj; } }; console.log(data.getRow(2).rowSample); console.log(data.getRow(5).rowSample); // will throw "Uncaught Error: Undefined trackObject key: row5" 

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