Search code examples
javascriptnode.jsunderscore.jswritefile

Node create file and write selected object values to it


What is the best way to get values from a set of objects coming through my function and write those values into a csv file?

The objects will come through like this:

 [ { objectTo:                        
     { employeeName: 'John',         
       employeeID: '234234', 
       DOB: '2333'},         
    employeeCurrent: true,
    employeePast: false},  
  { objectTo:                        
     { employeeName: 'Janet',         
       employeeID: '23423432', 
       DOB: '23333' },        
    employeeCurrent:true,
    employeePast: false} ]

I want to get the objects like objects1.objectTo.employeeName, objects1.objectTo.DOB, objects1.employeeCurrent on one cell but write each objectTo in it's own row.

I've tried to loop through and set this using a for loop then passing in the value to writeFile but this doesn't work. What is the best way to do this?

I've also tried to use the library underscore to give me the values but this also is not working and just writes out the whole objects:

var objectsToFile = function(objectsTotal){

        objectsTotal = _.values(objectsTotal, function(value) {
            return value.objectTo.employeeName;
        });

        objectsTotal = _.values(objectsTotal, function(value) {
            return value.employeeCurrent;
        });

        objectsTotal = _.values(objectsTotal, function(value) {
            return value.employeePast;
        });

        writeFile('objectsTotalet.csv', util.inspect(objectsTotal), function(err) {
            if (err) console.log(err);
        });
    };

Expected output in CSV (objects1.objectTo.employeeName, objects1.objectTo.DOB, objects1.employeeCurrent):

John 2333 true Janet 23333 true


Solution

  • let obj = [ { objectTo:                        
     { employeeName: 'John',         
       employeeID: '234234', 
       DOB: '2333'},         
    employeeCurrent: true,
    employeePast: false},  
    { objectTo:                        
     { employeeName: 'Janet',         
       employeeID: '23423432', 
       DOB: '23333' },        
    employeeCurrent:true,
    employeePast: false} ]
    
    const csvString = obj.map(item => {
       return [item.objectTo.employeeName, item.objectTo.DOB, item.employeeCurrent]
    }).join('\n')
    console.log(csvString) 
    // John,2333,true
    // Janet,23333,true
    

    If you want both of them on the same row, just join them using ',' instead of '\n'

    Once you have your string, you can use fs to write them in a csv file