Home > other >  JavaScript: format CSV array to Json format
JavaScript: format CSV array to Json format

Time:09-15

I have the following array which I have extracted from csv file

array 
[

   { "Date;Department;Value": "2022-09-08;dept1;7856"},
   { "Date;Department;Value": "2022-09-08;dept2;9876"}
]

I need the following output:

[
 {
  "Date":"2022-09-08",
  "Department":"dept1",
  "Value":7856
 },
{
  "Date":"2022-09-08",
  "Department":"dept2",
  "Value":9876
 }
]

CodePudding user response:

That's quite doable, just take the problem step by step:

const array  = [
   { "Date;Department;Value": "2022-09-08;dept1;7856" },
   { "Date;Department;Value": "2022-09-08;dept2;9876" }
];

const result = array
  .map(Object.entries)           // Convert the objects to more easily accessible arrays.
  .map(([[k, v]]) => {           // Grab the key / value strings
    const keys = k.split(';');   // Split the keys into separate entries.
    const values = v.split(';'); // Split the values into separate entries.
    
    // Join the array of keys with the array of values, parsing numbers if possible.
    return keys.reduce((obj, key, i) => {
      obj[key] = isNaN(values[i]) ? values[i] : Number(values[i]);
      return obj;
    }, {});
  });
  
console.log(result);

  • Related