2013-07-04 35 views
0

我有相联系的数组:访问对象值的关联数组值

instrumentLookup: { 
    hh: {label: 'Hi Hat', type: 'hh'}, 
    kd: {label: 'Kick Drum', type: 'kd'}, 
    o1: {label: 'other1', type: 'o1'}, 
    o2: {label: 'other2', type: 'o2'} 
    } 

我认为这个结构确定,但有可能是一个更好的办法。

我想这个功能,在帕拉姆addedInstrument就会出现,相同的字符串作为标签,所以hh,​​,o1创建从该列表的工具,....:

addInstrument: function(addedIntrument) { 
    console.warn(addedIntrument); 
    var newLabel = this.defaults.instrumentLookup.addedIntrument.label; 
    var newType = addedIntrument; 
    console.warn(newLabel + ' ' + newType) 
    // push it to the list 
    // this.unusedInstruments.push({label:newLabel, type:newType}); 
} 

有这几个问题,随时回答任何或全部或建议的替代:

  • 如何访问对象属性当对象是关联数组的值?
  • 我应该将其更改为来自Associate数组的嵌套对象{type:{other attrs}}的数组[]吗?
+1

记住JavaScript对象是真正的[关联数组](http://en.wikipedia.org/wiki/Associative_array)和属性(即采取字符串作为键如地图)不是“索引”,如PHP的“关联数组”的定义。 – Paul

+0

[动态对象属性名称](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) –

回答

2

如何访问对象属性当对象是关联数组的值?

这很容易。你可以这样做:console.log(instrumentLookup.hh.label); //Hi Hat

console.log(instrumentLookup.hh['label']); //Hi Hat

我应该将其更改为[]数组嵌套对象:从关联数组{{类型其他ATTRS}}?

如果您需要数组行为,则应使用数组。

从评论:

那么为什么不instrumentLookup.addedIntrument.label工作?

addedInstrument不是instrumentLookup一员,所以你不能使用.访问它(这将是不确定的)。相反,你需要做的:instrumentLookup[addedInstrument]

我认为这个结构确定,但有可能是一个更好的办法。

您已经由type参数存储每个乐器,为什么重复它的对象里面?除非你有不止类型和标签,可以通过进一步简化这个:

var instrumentLookup = { hh: 'High Hat', 
         kd: 'Kick Drum', 
         o1: 'Other1', 
         o2: 'Other2'} 

和重写你的addInstrument方法:

addInstrument: function(addedInstrument) { 
    console.warn(addedIntrument); 
    var inst = this.defaults.instrumentLookcup[addedInstrument]; 
    if(inst) { 
    this.unusedInstruments.push({label:inst, type:addedInstrument}); 
    } 
} 
+0

可能的重复,那么为什么'instrumentLookup.addedIntrument.label'没有工作? –

3

您需要括号符号动态地访问属性名称。

instrumentLookup[ addedIntrument ].label