下划线过滤器,访问索引

underscore filter, access index

我有以下 javascript 代码

log = _.filter(r.logs, (function(o, i) {
  if (i === 0) {
    r.createdAt = moment(o.updatedAt).format("lll");
  } else {
    r.createdAt = "";
  }
  if (i === 1) {
    r.authorisedAt = moment(o.updatedAt).format("lll");
    r.authorisedBy = o.user;
  } else {
    r.authorisedAt = "";
    r.authorisedBy = "";
  }
  if (i === 2) {
    r.receivedAt = moment(o.updatedAt).format("lll");
    r.receivedBy = o.user;
  } else {
    r.receivedAt = "";
    r.receivedBy = "";
  }
  if (i === 3) {
    r.creditedAt = moment(o.updatedAt).format("lll");
    return r.creditedBy = o.user;
  } else {
    r.creditedAt = "";
    return r.creditedBy = "";
  }
}));

r.logs

的结构
{ user: 54ba76d3a14c9766bc6e0c2f,
  updatedAt: Mon Feb 16 2015 16:38:46 GMT+0000 (GMT),
  status: 'new',
  comments: 'test return',
  _id: 54e21d16608eb7bc20d5451b } 0
{ user: 54ba7c5b21f9fbb867222a95,
  updatedAt: Mon Feb 16 2015 16:40:14 GMT+0000 (GMT),
  status: 'authorised',
  comments: 'EP02-BR2 is a sample, therefore return not authorised',
  _id: 54e21d6e608eb7bc20d5451c } 1
{ user: 54ba7c5b21f9fbb867222a95,
  updatedAt: Mon Feb 16 2015 16:41:11 GMT+0000 (GMT),
  status: 'received',
  comments: 'i only got one item for EP02-BL1',
  _id: 54e21da7608eb7bc20d5451d } 2
{ user: 54ba7c5b21f9fbb867222a95,
  updatedAt: Mon Feb 16 2015 16:42:59 GMT+0000 (GMT),
  status: 'credited',
  comments: 'credit sent',
  _id: 54e21e13608eb7bc20d5451e } 3

这可行,但想知道它是否可以更简单地完成?

我会使用 switch() 语句:

log = _.filter(r.logs, (function(o, i) {
    r.createdAt = r.authorisedAt = r.authorisedBy = r.receivedAt = r.receivedBy = r.creditedAt = "";
    toMoment = moment(o.updatedAt).format("lll");
    switch(i){
        case 0:
            r.createdAt = toMoment;
            break;
        case 1:
            r.authorisedAt = toMoment;
            r.authorisedBy = o.user;
            break;
        case 2:
            r.receivedAt = toMoment;
            r.receivedBy = o.user;
            break;
        case 3:
            r.creditedAt = toMoment;
            return r.creditedBy = o.user;
            break;
    }
}));

基于@Mihai lorga 的回答。这是另一个调整

llog = _.filter(r.logs, (function(o, i) {
r.createdAt = r.authorisedAt = r.authorisedBy = r.receivedAt = r.receivedBy = r.creditedAt = "";
var format = "lll";
switch(i){
    case 0:
        r.createdAt = applyFormat(o.updatedAt,format );
        break;
    case 1:
        r.authorisedAt = applyFormat(o.updatedAt,format );
        r.authorisedBy = o.user;
        break;
    case 2:
        r.receivedAt = applyFormat(o.updatedAt,format );
        r.receivedBy = o.user;
        break;
    case 3:
        r.creditedAt = applyFormat(o.updatedAt,format );
        return r.creditedBy = o.user;
        break;
}
}));
function applyFormat(date,format){
return moment(date).format(format);
 }

如果将来您需要更改任何格式或日期,则无需更改每一行