[英]Can I combine array destructuring and .trim()?
I am having an array of strings coming from a CSV file which I destructure in my node.js app. 我有一个来自CSV文件的字符串数组,我在node.js应用程序中对其进行了分解。
Now I need the strings trimmed with .trim() but I wonder if there is an immediate way to do this. 现在,我需要用.trim()修饰的字符串,但是我想知道是否有立即执行此操作的方法。 The below doesn't work: 以下无效:
// writing object with returned arrays retrieved from CSV
playerRecordsArr.forEach((playerRecord) => {
const [id.trim(), customFlag.trim(), countryCode.trim()] = playerRecord;
resultObject[steamID] = {
playerData: { customFlag, countryCode },
};
});
I guess the way to do it would be this, but I'd lose the destructuring goodness: 我想这样做的方法是这样,但是我会失去破坏性的优势:
// writing object with returned arrays retrieved from CSV
playerRecordsArr.forEach((playerRecord) => {
const id = playerRecord[0].trim();
const customFlag = playerRecord[1].trim();
const countryCode = playerRecord[2].trim();
resultObject[steamID] = {
playerData: { customFlag, countryCode },
};
});
map
can be used to transform all elements of an array, but I would recommend to do apply trim
individually at the place where you are using the value: map
可以用于转换数组的所有元素,但是我建议在使用该值的地方单独应用trim
:
for (const [id, flag, country] of playerRecordsArr) {
resultObject[id.trim()] = {
playerData: { customFlag: flag.trim(), countryCode: country.trim() },
};
}
const playerRecord = [' one ', 'two ', 10000]; const trimIfString = x => typeof x === 'string' ? x.trim() : x; const [id, customFlag, countryCode] = playerRecord.map(trimIfString); console.log(playerRecord) console.log(playerRecord.map(trimIfString))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.