[英]Convert any null or falsy values in an array to blank string "" values Javascript
I did an API get request and put the results in an array.我做了一个 API get 请求并将结果放在一个数组中。 Some of the results may come back undefined or null - later in the script I need to pass along the values as strings - so if there is no value I need it to pass along as a "" string value.
一些结果可能返回未定义或 null - 在脚本的后面我需要将值作为字符串传递 - 所以如果没有值我需要它作为“”字符串值传递。 But how can I loop through the array and make sure that any non-value values are stored as a string with
""
?但是我如何遍历数组并确保所有非值都存储为带有
""
的字符串?
var dealresponse = UrlFetchApp.fetch(dealurl, options);
dealresponse = JSON.parse(dealresponse.getContentText());
var propertyAddress = dealresponse.data["9bd1d8c4f07f5795fd8bffb16f3b63c6547d7d3a"];
var leadType = dealresponse.data["c4ecbe01c3494d1be52432f4a3194ede3a50c0f8"];
var dealType = dealresponse.data["a4269fb4730cf7fd1787752be94eacbc4b0de24e"];
var dealSource = dealresponse.data["d76fa2d6f8454a51f7d64d981cd9320877bc2ea0"];
var dealArray = [propertyAddress, leadType, dealType, dealSource];
Logger.log(dealArray);
I'd like to process dealArray
at the end and just make sure blanks are actual ""
string values.我想在最后处理
dealArray
并确保空白是实际的""
字符串值。 I don't want to delete or remove these values from the object, I just want to convert anything falsy to a string "" (I believe that "" is considered falsy in and of itself)我不想从 object 中删除或删除这些值,我只想将任何虚假的内容转换为字符串“”(我相信“”本身被认为是虚假的)
If you have no other falsy values than undefined
or null
, you could take a logical OR ||
如果除
undefined
或null null
没有其他虚假值,则可以采用逻辑或||
dealArray = dealArray.map(v => v || '')
Otherwise take a Nullish coalescing operator ??
否则采用Nullish 合并运算符
??
. .
dealArray = dealArray.map(v => v ?? '')
One approach is looping throught the array,一种方法是遍历数组,
var dealArray = [propertyAddress, leadType, dealType, dealSource];
const result = dealArray.map((deal) => deal ? deal: "");
Another approach is, initialize to empty if the value is not present.另一种方法是,如果值不存在,则初始化为空。
var propertyAddress = dealresponse.data["9bd1d8c4f07f5795fd8bffb16f3b63c6547d7d3a"] || '';
var leadType = dealresponse.data["c4ecbe01c3494d1be52432f4a3194ede3a50c0f8"] || '';
var dealType = dealresponse.data["a4269fb4730cf7fd1787752be94eacbc4b0de24e"] || '';
var dealSource = dealresponse.data["d76fa2d6f8454a51f7d64d981cd9320877bc2ea0"] || '';
var dealArray = [propertyAddress, leadType, dealType, dealSource];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.