Flatten js object and return in CSV format - Node.js File

Node.js examples for File:CSV

Description

Flatten js object and return in CSV format

Demo Code

exports.flattenjs2csv = function(obj) { 
    //  w  w  w  . ja  v a2  s.  c o  m
    var flattenjs2csv = function(obj) {
        
        var addCol = function(line, obj) {
            if (line.length > 0) line += ',';
            line += JSON.stringify(obj).replace(/"/g, '');
            return line;
        };
        
        var addCols = function (dest, objA, objB){
            objB.forEach(function (val, index) {
                if (index > 0)     
                    dest.push(addCol(objA[1], val));
                else if (dest.length === 0) 
                    dest.push(addCol(objA[0], val));     
            });
            return dest;
        };
            
        var flatObj = function(obj) {
            if (Array.isArray(obj))
                return ['',''];
            if ((typeof obj !== 'object') || (obj instanceof Date))
               return ['item', addCol('',obj)];
            var res = ['','']; 
            for (var i in obj) {
                if ((typeof obj[i] !== 'object') || (obj[i] instanceof Date)) {
                    res[0] = addCol(res[0], i);
                    res[1] = addCol(res[1], obj[i]);   
                }
            }
            return res;   
        };
        
        var res = [];
        var objA = flatObj(obj); 
        for (var i in obj) {
            if (Array.isArray(obj[i])) {
                for (var x in obj[i]) {
                    if(Object.prototype.hasOwnProperty.call( obj[i], x)){
                        var objB = flattenjs2csv(obj[i][x]); 
                        res = addCols(res, objA, objB);
                    }
                }
            }    
        }
        return (res.length===0) ? objA : res;
    };
    
    var res = '';
    flattenjs2csv(obj).forEach( function(entry) {
        res += entry + '\n';   
    });
    return res;
};

Related Tutorials