4

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.

marc_s
760k186 gold badges1.4k silver badges1.5k bronze badges
asked Apr 2, 2018 at 6:56
4

4 Answers 4

8

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)

answered Apr 7, 2020 at 13:20
Sign up to request clarification or add additional context in comments.

2 Comments

Really nice answer! you could also trim the keys and values, incase there are leading/trailing spaces, in poorly formatted .csv files etc. by changing your return inside the reduce callback to (object[curr.trim()] = values[i].trim(), object)
Yeah, you are right, thank you for your suggestion, it is really a good solution for irregular data @AlexL
3

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

answered Apr 2, 2018 at 7:23

Comments

3

Here's some code I wrote for doing this:

const lineRegex = /((\\\n)|[^\n])+/g;
const datumRegex = /,?(("(\\"|.)+?")|([^",][^,]*))?/g;
const array2d: string[][] = rawCsvFile.match(lineRegex).map((row) => 
 row.match(datumRegex).map((datum) => datum.replace(/^,?"?|"$/g, "").trim()),
);

The regexes above will handle newlines within datums as well as escaped quotes and quoted commas. And if you want to create an array of objects where each row is an object with the first rows values as prop names, you can use this.

console.log(array2d); // [[name, age], ["joe", 35], ["martha", 28]]
const out = [];
const propsRow = array2d[0];
array2d.forEach((row, i) => {
 if (i === 0) { return; }
 const addMe: any = {};
 row.forEach((datum, j) => addMe[propsRow[j]] = datum);
 out.push(addMe);
});
console.log(out); // [{name: "joe", age: 35}, {name: "martha", age: 28}]
answered Oct 24, 2018 at 21:30

Comments

1

You can get the data from CSV To Array by using below below code

 /**
 * Convert data in CSV (comma separated value) format to a javascript array.
 *
 * Values are separated by a comma, or by a custom one character delimeter.
 * Rows are separated by a new-line character.
 *
 * Leading and trailing spaces and tabs are ignored.
 * Values may optionally be enclosed by double quotes.
 * Values containing a special character (comma's, double-quotes, or new-lines)
 * must be enclosed by double-quotes.
 * Embedded double-quotes must be represented by a pair of consecutive 
 * double-quotes.
 *
 * Example usage:
 * var csv = '"x", "y", "z"\n12.3, 2.3, 8.7\n4.5, 1.2, -5.6\n';
 * var array = csv2array(csv);
 * 
 * Author: Jos de Jong, 2010
 * 
 * @param {string} data The data in CSV format.
 * @param {string} delimeter [optional] a custom delimeter. Comma ',' by default
 * The Delimeter must be a single character.
 * @return {Array} array A two dimensional array containing the data
 * @throw {String} error The method throws an error when there is an
 * error in the provided data.
 */ 
function csv2array(data, delimeter) {
 // Retrieve the delimeter
 if (delimeter == undefined) 
 delimeter = ',';
 if (delimeter && delimeter.length > 1)
 delimeter = ',';
 // initialize variables
 var newline = '\n';
 var eof = '';
 var i = 0;
 var c = data.charAt(i);
 var row = 0;
 var col = 0;
 var array = new Array();
 while (c != eof) {
 // skip whitespaces
 while (c == ' ' || c == '\t' || c == '\r') {
 c = data.charAt(++i); // read next char
 }
 // get value
 var value = "";
 if (c == '\"') {
 // value enclosed by double-quotes
 c = data.charAt(++i);
 do {
 if (c != '\"') {
 // read a regular character and go to the next character
 value += c;
 c = data.charAt(++i);
 }
 if (c == '\"') {
 // check for escaped double-quote
 var cnext = data.charAt(i+1);
 if (cnext == '\"') {
 // this is an escaped double-quote. 
 // Add a double-quote to the value, and move two characters ahead.
 value += '\"';
 i += 2;
 c = data.charAt(i);
 }
 }
 }
 while (c != eof && c != '\"');
 if (c == eof) {
 throw "Unexpected end of data, double-quote expected";
 }
 c = data.charAt(++i);
 }
 else {
 // value without quotes
 while (c != eof && c != delimeter && c!= newline && c != ' ' && c != '\t' && c != '\r') {
 value += c;
 c = data.charAt(++i);
 }
 }
 // add the value to the array
 if (array.length <= row) 
 array.push(new Array());
 array[row].push(value);
 // skip whitespaces
 while (c == ' ' || c == '\t' || c == '\r') {
 c = data.charAt(++i);
 }
 // go to the next row or column
 if (c == delimeter) {
 // to the next column
 col++;
 }
 else if (c == newline) {
 // to the next row
 col = 0;
 row++;
 }
 else if (c != eof) {
 // unexpected character
 throw "Delimiter expected after character " + i;
 }
 // go to the next character
 c = data.charAt(++i);
 } 
 return array;
}

Working Example Demo Link : http://www.speqmath.com/tutorials/csv2array/

answered Apr 2, 2018 at 7:03

1 Comment

This code is broken. It throw error on single " and \t

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.