将对象 属性 键设置为变量值

Set object property key to variable value

我正在动态创建一个对象,并想将 属性(也是一个对象)设置为变量的值。

我的代码:

var guid, block, lot, muni, county, owner, prop_loc;

guid = 'Some unique value';
//code to set the other variable values here...

var menuItem = new MenuItem({
    id: 'basic',
    label: 'Report',
    onClick: lang.hitch(this, function () {
        topic.publish('basicReportWidget/reportFromIdentify', {
            guid : {  //set this to the guid string value
                block: block,
                lot: lot,
                muni: muni,
                county: county,
                owner: owner,
                prop_loc: prop_loc,
                type: 'basic'
            }
        });
    })
});

如果所有这些都是您的代码,那么只需将对象替换为您的 guid 变量的 guid 键即可,如下所示:

var guid, block, lot, muni, county, owner, prop_loc;

guid = 'Some unique value';
//code to set the other variable values here...

var menuItem = new MenuItem({
    id: 'basic',
    label: 'Report',
    onClick: lang.hitch(this, function () {
        topic.publish('basicReportWidget/reportFromIdentify', {
            guid : guid
        });
    })
});

否则,如果您出于某种原因无法修改该 menuItem 对象,您可能会通过类似以下内容覆盖 onClick 函数:

menuItem.onClick = function() {
    lang.hitch(this, function () {
        topic.publish('basicReportWidget/reportFromIdentify', {
            guid : guid
        });
    };

正如 Rayon 所说,您可以使用括号表示法来动态设置对象属性。

像这样的东西应该有用...

var guid, block, lot, muni, county, owner, prop_loc;

guid = 'Some unique value';

var menuItem = new MenuItem({
  id: 'basic',
  label: 'Report',
  onClick: lang.hitch(this, function () {
    var obj = {};
    obj[guid] = { 
      block: block,
      lot: lot,
      muni: muni,
      county: county,
      owner: owner,
      prop_loc: prop_loc,
      type: 'basic'
    };
    topic.publish('basicReportWidget/reportFromIdentify', obj);
  })
});