我有一个来自CSV文件的字符串数组,我在node.js app中进行了解构。
现在我需要用.trim()修剪的字符串,但我想知道是否有一个直接的方法来做到这一点。以下不起作用:
// writing object with returned arrays retrieved from CSV
playerRecordsArr.forEach((playerRecord) => {
const [id.trim(), customFlag.trim(), countryCode.trim()] = playerRecord;
resultObject[steamID] = {
playerData: { customFlag, countryCode },
};
});
我想这样做的方法就是这样,但我失去了解构的善良:
// 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 },
};
});
答案 0 :(得分:2)
map
可用于转换数组的所有元素,但我建议您在使用该值的位置单独应用trim
:
for (const [id, flag, country] of playerRecordsArr) {
resultObject[id.trim()] = {
playerData: { customFlag: flag.trim(), countryCode: country.trim() },
};
}
答案 1 :(得分:1)
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))