如何在javascript / vuejs中使用if语句

时间:2017-06-05 04:53:40

标签: javascript vue.js mapping vuejs2

我正在Vuejs中构建一个小应用程序,我正在获取响应数据,并且我将它映射到一个变量,我有几个具有空数组的元素,所以我想要映射检查条件并相应地映射。这是我的代码:

this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
},{
    if(i.meeting.meeting_summaries)
    {
        'meeting_summaries': i.meeting_summaries.map(ms => ({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
    }

},

2 个答案:

答案 0 :(得分:1)

map纯粹是功能性的,它不会修改元素而是返回一个新形成的数组,所以你可以这样做:

this.model = a.map(i => {
  var item = {}
  item['id']= i.id,
  item['meeting_date']= i.schedule,
  item['meeting_call']= i.type,
  item['event_type']= i.event_type,
  item['venue']= i.venue,
  item['with_client']= i.with_client
  if(i.meeting && i.meeting.meeting_summaries) {
     item['meeting_summaries']= i.meeting.meeting_summaries.map(ms =>({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
  }else {
   item['meeting_summaries'] = []
  }
 return item
}

答案 1 :(得分:0)

在您的情况下,您可以切换到ternary expression

this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
}, (i.meeting.meeting_summaries) ? { // if condition is met
    'meeting_summaries': i.meeting_summaries.map(ms => ({
        client_name: ms.client_name,
        nature: ms.nature,
        action: ms.action,
        mention: ms.user_id,
        feedback: ms.feedback
    }))
} : {} // otherwise don't do anything

这个想法如下:



const a = [1, 2, 3, 4, 5];

const b = a.map(number => Object.assign({a: number}, 
  (number > 2) ? {b: ++number} : {}, // add 'b' for numbers > 2
  (number % 2 === 0) ? {c: number + ' is even'} : {} // add 'c' for even numbers
  ))
  
console.log(b)