I have data in CSV format data and want to convert into JSON format using Javascript.
Following are csv format:
[Test.csv]
id;name;author
integer;st
Here is my try on your SPECIFIC example. I know it is an old question but I have used current methods
const titlesCsv = `id;name;author
integer;string;authors:n
1;To Kill an Mockingbird;1
2;Lord of the Rings;2
3;Hamlet;3`
const authorsCsv = `id;name
integer;string
1;Harper Lee
2;JRR Tolkien
3;William Shakespeare`
const parseCsv = csv => {
let lines = csv.split("\n");
const header = lines.shift().split(";")
lines.shift(); // get rid of definitions
return lines.map(line => {
const bits = line.split(";")
let obj = {};
header.forEach((h, i) => obj[h] = bits[i]); // or use reduce here
return obj;
})
};
const titles = parseCsv(titlesCsv)
const authors = parseCsv(authorsCsv)
const books = titles.map(title => {
return {
id: title.id,
name: title.name,
author: authors.find(author => author.id === title.author).name
}
})
console.log(books)