下划线过滤器,访问索引

时间:2015-02-17 10:23:02

标签: javascript underscore.js

我有以下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

这有效,但想知道它是否可以更简单?

2 个答案:

答案 0 :(得分:1)

我会使用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;
    }
}));

答案 1 :(得分:0)

基于@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);
 }

通过这种方式,如果以后需要更改格式或日期的任何内容,则不需要更改每一行