更好的方法来实现此目的,而不是立即调用函数表达式?

时间:2018-07-12 14:43:01

标签: javascript ecmascript-6

我正在寻找更好的方法来实现这一目标。除了使用分配给type

的IIFE之外,还有其他更好的方法
inputSources: inputSources
    .map(({ _objectId, caption: inputCaption, lookupId, picklistId, type }) => ({ 
      _id: _objectId,
      caption: inputCaption,
      participantCriteriaId: _id,
      referenceId: (lookupId || picklistId) || null,
      type: (() => {
        if (type === 'identifier' && lookupId) return 'lookup';
        if (type === 'identifier' && !lookupId) return 'key';
        return type;
      })(),
    })),
  

更新:ESLint不喜欢嵌套三元运算符

1 个答案:

答案 0 :(得分:3)

我绝对会推荐三元运算符,这是这里最易读的选项。 (我很高兴在那里同意ESLint的意见。)

但是您可以简单地将语句移到对象文字之前:

inputSources.map(({ _objectId, caption: inputCaption, lookupId, picklistId, type }) => {
  if (type === 'identifier')
    type = lookupId ? 'lookup' : 'key';
  return { 
    _id: _objectId,
    caption: inputCaption,
    participantCriteriaId: _id,
    referenceId: lookupId || picklistId || null,
    type,
  };
}),