0

I am trying to edit a single element in an array built by fast-csv in Node.JS.

Fast-csv is editing all the columns when a single array index is included, and no array indexes when a 2D array index is used.

The question is, is it possible to edit a single element from a CSV in javascript?

Input (input.csv):

hello,1,'1',forty-two, 
yellow,brown,red,orange

Current output:

[ 'hello', '1', 696, 'forty-two', '' ]
[ 'yellow', 'brown', 696, 'orange' ]

Target output:

[ 'hello', 'julian', 696, 'forty-two', '' ]
[ 'yellow', 'brown', 696, 'orange' ]

Logic:

var fs = require('fs');
var csv = require('fast-csv');


fs.createReadStream('./IOinput/input.csv')
    .pipe(csv())
    .on('data', function(data){
        //console.log(data);
        data[0][1] = 'julian';
        data[2] = 696;

        console.log(data);
    })

    .on('end', function(data){
        console.log('Read finished');
    })

Dependencies:

npm install fast-csv
1
  • data[2] = 696 works so why don't you try data[1] = 'julian' instead of data[0][1] Commented May 11, 2016 at 2:49

1 Answer 1

2

According to the documentation the data event is fired when a record or a row is read in. So what I would do is create an array and push each record onto the array then make the changes at the end. Another way to do it is to keep a counter of what row is being read in and branching accordingly. I personally think the first option is easier. Here's how it could look:

var fs = require('fs');
var csv = require('fast-csv');

var dataArr = [];
fs.createReadStream('./IOinput/input.csv')
    .pipe(csv())
    .on('data', function(data){
        dataArr.push(data); // Add a row
    })

    .on('end', function(){
        dataArr[0][1] = 'julian';
        dataArr[0][2] = 696;
        dataArr[1][2] = 696;
        console.log(dataArr);
        console.log('Read finished');
    })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.