我有以下功能:
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 }
...
]
我想要一个过滤掉空行的所有电子邮件的数组。通过上面的代码我得到:
[ K@DF.COM, K@DF.COM, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
如何去掉空行?
最佳答案
您必须先获取EMAIL
属性,然后过滤空或未定义的条目:
var rows = [
{ EMAIL: 'a@b.com', prop: 'bla' },
{ EMAIL: '', prop: 'bla' },
{ EMAIL: undefined },
{ EMAIL: 'd@b.com', prop: 'bla' },
{ },
undefined
];
var emails = rows
.map(function (row) { return row && row.EMAIL; })
.filter(Boolean);
console.log(emails);
它无法以其他方式工作的原因是您需要过滤掉空的 EMAIL 字段,但是您通过将行与空字符串进行比较来过滤行。空行 ({}
) 将无法通过过滤器测试。
要使其以其他方式工作,您需要首先根据行的 EMAIL 属性过滤行,然后映射:
var rows = [
{ EMAIL: 'a@b.com', prop: 'bla' },
{ EMAIL: '', prop: 'bla' },
{ EMAIL: undefined },
{ EMAIL: 'd@b.com', prop: 'bla' },
{ },
undefined
];
var emails = rows
.filter(function (row) { return row && row.EMAIL; })
.map(function (row) { return row.EMAIL; });
console.log(emails);
关于javascript - 应用脚本 : filter out empty elements from array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55054012/