简体   繁体   中英

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.

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 },
    };
  });

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() },
    };
}

 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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM