vatsa
vatsa

Reputation: 49

Converting csv data into an array format

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 coloumns 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.

Upvotes: 3

Views: 19885

Answers (4)

Raos
Raos

Reputation: 394

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)

Upvotes: 7

Seph Reed
Seph Reed

Reputation: 10878

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}]

Upvotes: 2

user1636522
user1636522

Reputation:

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

Upvotes: 2

SantoshK
SantoshK

Reputation: 1877

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/

Upvotes: 0

Related Questions