Reputation: 60
I am having an array of strings coming from a CSV file which I destructure in my node.js app.
Now I need the strings trimmed with .trim() but I wonder if there is an immediate way to do this. 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 },
};
});
Upvotes: 1
Views: 1264
Reputation: 18156
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))
Upvotes: 2
Reputation: 665145
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:
for (const [id, flag, country] of playerRecordsArr) {
resultObject[id.trim()] = {
playerData: { customFlag: flag.trim(), countryCode: country.trim() },
};
}
Upvotes: 2