简体   繁体   English

javascript对象索引键

[英]javascript object index keys

I'm trying to figure out the best way to structure my javascript object. 我正在尝试找出构造JavaScript对象的最佳方法。 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 . 理想情况下,我希望能够通过在“行”层(即row1row2建立索引来修改此对象。 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. 即上面的对象将通过调用trackObject.row1返回我需要的对象,但是由于row1部分需要动态,因此我不确定如何从这一点动态对其进行索引。

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... ) 我尝试了一些变体,例如不将trackObject为数组,而是将对象更改为row1并将其更改为"row1":{rowId...但后来我无法引用其嵌套的对象属性( {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... 我之前用JSON中的键设置对象,并且可以很好地通过键索引,但是由于某些原因,我在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. 构造javascript对象的便捷方法
Consider using custom getter method which accepts row index/number as a parameter: 考虑使用自定义getter方法,该方法接受索引/数字作为参数:

 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" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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