split String, then count and convert to json array

277 Views Asked by At

I have a url to read file in my nodejs application. What I wanna do three things in here. First read file through that url. Second I want to addition the count if value is the same and final is convert to json. Here is the format that I want.

[ 
 {
   value : '106',
   count : 1 
 },{
   value : '109',
   count : 2
 }
]

Here is the file format

value, count, 106, 1, 109, 2, 111,2

I try to use csv-parse and csvtojson node module but it different to manipulate the way the I want. Those modules return the json but I want to manipulate the json like if value are the same, I want to addition the count.

Thanks.

1

There are 1 best solutions below

0
lilezek On BEST ANSWER

Try this:

const arr = csvString.split(",");
const result = [];
for (let i = 2; i < arr.length; i+=2) {
  result.push({
    value: arr[i],
    count: arr[i+1]
  });
}