-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwork_csv.ts
More file actions
31 lines (24 loc) · 821 Bytes
/
work_csv.ts
File metadata and controls
31 lines (24 loc) · 821 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import * as fs from "fs/promises";
interface RecordType {
name: string;
age: number;
role: string;
}
const records: RecordType[] = [
{ name: "Alice", age: 30, role: "developer" },
{ name: "Bob", age: 25, role: "designer" },
];
const header = Object.keys(records[0]) as (keyof RecordType)[];
const rows = records.map((obj) => header.map((h) => String(obj[h])).join(","));
const csv = [header.join(","), ...rows].join("\n");
(async () => {
await fs.writeFile("output.csv", csv, "utf-8");
const raw = await fs.readFile("output.csv", "utf-8");
const [head, ...lines] = raw.trim().split("\n");
const keys = head.split(",");
const parsed = lines.map((line) => {
const values = line.split(",");
return Object.fromEntries(values.map((v, i) => [keys[i], v]));
});
console.log(parsed);
})();