0

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
 }
]
1
  • You can parse a file with any delineator with d3, such as a semicolon rather than a comma, see here for an example. Commented Sep 14, 2022 at 15:52

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.