Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a CSV string into a 2d object

Tags:

javascript

I'm currently trying to figure out how to parse a csv string into an object that will allow me to go to a customers name in the first object and then being able to access the said customers information in a sub array based off of which name.

csvString = "roll R coaster,0124454,20.21\n

I know that the .split() function will split the string based off a delimiter and place it in an array. If I use "\n" as my first delimiter, 5 array elements are created for each client followed by their respective information.

array[0] = "roll R coaster,0124454,20.21"
like image 851
Jeffery Wallace Avatar asked Mar 14 '26 03:03

Jeffery Wallace


1 Answers

I think this code does pretty much what you need.

csvString = "roll R coaster,0124454,20.21\n  Sammy Smocks,000006,(20.20)\n maxwell BLANCO  ,002125,(15),\n Will   Monsters,003576,6.9,15\n Trank   Burger,103529,9.56,5";


const objects = csvString.split('\n ')
  .map(x => {
    const [name, TransactionNumber, TrAm] = x.split(',');
    TransactionAmount = TrAm[0] === '(' ? +TrAm.slice(1, -1) : +TrAm;
    
    FullName = name
    	.replace(/^\s{2,}/g, ' ')
      .replace(/\s{3}/g, '  ')
      .replace(/\s{2}$/g, ' ');
            
    const [FirstName, MiddleName, LastName] = FullName.split(' ');
    
    return {
      FirstName, 
      MiddleName, 
      LastName, 
      TransactionNumber,
      TransactionAmount
    }
  });

console.log(objects);
like image 168
Boris Lobanov Avatar answered Mar 16 '26 16:03

Boris Lobanov