有没有更好的方法来检查标志,然后在 javascript 中的函数中设置可选参数? (在js对象中写函数)

Is there a better way to check a flag and then set optional parameter in a function in javascript? (Writing function in a js object)

刚在做electron项目的时候遇到过这种情况。下面是一个 pouchDB put 函数,我试图用它上传附件

我现在的代码是这样的:

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: {
    testCaseFile: {
      type: tAttachment.type,
      data: tAttachment,
    },
  },
  // ...
});

问题是我想检查是否设置了变量 tAttachment。如果不是,我不想在 pouchDB 中添加附件,如果它已设置,我希望它如上所述。为此,我通常会编写两个重复代码并添加 _attachment 选项。我想知道是否有更好的方法来做到这一点。是这样的吗? (以下无效):

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: {
    testCaseFile: {
      function() {
        if (tAttachment) {
          returnData = {
            type: tAttachment.type,
            data: tAttachment,
          };
        } else {
          returnData = null;
        }
        return returnData;
      },
    },
  },
});

我可能会在创建新实体之前声明附件地图:

const attachments = {};

if (tAttachment) {
  attachments.testCaseFile =  {
    type: tAttachment.type,
    data: tAttachment,
  }
}

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: attachments,
  // ...
});