d3.js JavaScript:将CSV数组格式化为Json格式

xlpyo6sf  于 2022-11-12  发布在  Java
关注(0)|答案(1)|浏览(108)

我有下面的数组,我已经从csv文件提取

array 
[

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

我需要以下输出:

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

e7arh2l61#

这是完全可行的,只要把问题一步一步来:

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

相关问题