应用脚本:从数组中过滤掉空元素

问题描述 投票:0回答:2

enter image description here

我有以下功能:

  var rows = sheet2Json(sheet);

  var emails = rows.filter(function (el) { //ONLY CHECKED ROWS.
         return el != "";
    })
               .map(function (row) { //ONLY CHECKED ROWS.
      return row['EMAIL'];
    });  



  Logger.log(emails)
  return (emails);
}

rows在一个对象数组中生成表单,如下所示:

[{ EMAIL=xxx,  TEMPLATE=CONSULT, Index=Thu Jan 24 16:26:02 GMT-05:00 2019 }
...
]

我想要一个过滤掉空行的所有电子邮件的数组。使用上面的代码,我得到:

[ [email protected], [email protected],  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]

我怎样才能摆脱空行?

javascript google-apps-script
2个回答
2
投票

您必须先获取EMAIL属性,然后过滤空或未定义的条目:

var rows = [
  { EMAIL: '[email protected]', prop: 'bla' },
  { EMAIL: '', prop: 'bla' },
  { EMAIL: undefined },
  { EMAIL: '[email protected]', prop: 'bla' },
  { },
  undefined
];

var emails = rows
  .map(function (row) { return row && row.EMAIL; })
  .filter(Boolean);

console.log(emails);

它不是以另一种方式工作的原因是你需要过滤掉空的EMAIL字段,但是你通过将它们与空字符串进行比较来过滤行。空行({})不会通过您的过滤器测试。

要使其以其他方式工作,您需要首先根据其EMAIL属性过滤行,然后映射:

var rows = [
  { EMAIL: '[email protected]', prop: 'bla' },
  { EMAIL: '', prop: 'bla' },
  { EMAIL: undefined },
  { EMAIL: '[email protected]', prop: 'bla' },
  { },
  undefined
];

var emails = rows
  .filter(function (row) { return row && row.EMAIL; })
  .map(function (row) { return row.EMAIL; });

console.log(emails);

1
投票
  • 您想使用Google Apps脚本从EMAIL这样的对象中检索[{ EMAIL=xxx, TEMPLATE=CONSULT, Index=Thu Jan 24 16:26:02 GMT-05:00 2019 }...]的值。

如果我的理解是正确的,那么这个修改怎么样?在这个修改中,我使用了reduce()。请将此视为几个答案中的一个。

Modified script:

var emails = rows.reduce(function (ar, row) {
  row['EMAIL'] && ar.push(row['EMAIL']);
  return ar;
}, []);

Reference:

© www.soinside.com 2019 - 2024. All rights reserved.