I am trying to form a wordCloud using jquery. I have a csv file to be read and use that data to form a wordCloud.
I have columns in my .csv
file as
text weight
Lorem 15
Ipsum 9
and so on.
But the input data needs to be in the following format
var word_array = [
{ text: "Lorem", weight: 15 },
{ text: "Ipsum", weight: 9 },
{ text: "Dolor", weight: 6 },
{ text: "Sit", weight: 7 }
];
How should I convert my .csv
data into the above format to be able to form the word cloud. Please attach the code if possible. I am doing all this in my html page. Thank you.
Here is a possible solution in ES6:
const csv2json = (str, delimiter = ',') => {
const titles = str.slice(0, str.indexOf('\n')).split(delimiter);
const rows = str.slice(str.indexOf('\n') + 1).split('\n');
return rows.map(row => {
const values = row.split(delimiter);
return titles.reduce((object, curr, i) => (object[curr] = values[i], object), {})
});
};
let csv = "text weight\nLorem 15\nIpsum 9";
let word_array = csv2json(csv,' ');
console.log(word_array)
Here is a possible solution :
var csv = "";
csv += "text weight\n";
csv += "Lorem 15\n";
csv += "Ipsum 9";
var lines = csv.split("\n");
var titles = lines[0].split(" ");
var data = new Array(lines.length - 1);
for (var i = 1; i < lines.length; i++) {
data[i - 1] = {};
lines[i] = lines[i].split(" ");
for (var j = 0; j < titles.length; j++) {
data[i - 1][titles[j]] = lines[i][j];
}
}
console.log(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With