自己手搓的CSV解释器
class csv {constructor( csvData ){
this.csvData = csvData
}
readAsArrays( backobj=false ){
let data = ( function( csv ){
let ret = []
csv.forEach( function( v ){
ret.push( v.split( "," ))
})
return ret
} )( this.csvData.split( "\n" ) )
if( backobj == false ){
return data
} else {
return {
result : data,
json : JSON.stringify( data, 0, 4 ),
pushTo : function( array ){
array.concat( data )
return this
},
then : function( func ){
func( this, data )
return this
},
each : function( callback ){
for( let line in data ){
for( let pos in data ){
callback( data, [ line, pos ] )
//value index
}
}
return this
}
}
}
}
readAsList( backobj=false ){
let data = ( function( csv ){
let ret = {}
for( let key in csv ){
ret[ csv[ key ] ] = []
for( let line in csv ){
if( line > 0 ){
ret[ csv[ key ] ]
.push( csv[ line ][ key ] )
}
}
}
return ret
} )( this.readAsArrays() )
if( backobj == false ){
return data
} else {
return {
result : data,
json : JSON.stringify( data, 0, 4 ),
pushTo : function( obj ){
Object.assign( obj, data )
return this
},
then : function( func ){
func( this, data )
return this
},
each : function( callback ){
for( let line of Object.keys( data ) ){
for( let pos in data ){
callback( data, [ line, pos ] )
//value index
}
}
return this
}
}
}
}
readAsObject( backobj=false ){
let data = ( function( csv ){
let ret = {}
for( let line in csv ){
eval( "ret." + csv
.slice( 0, -1 )
.join( "." ) + "='" + csv
.slice( -1 )
.join( " " ) + "'" )
}
return ret
} )( this.readAsArrays() )
if( backobj == false ){
return data
} else {
return {
result : data,
json : JSON.stringify( data, 0, 4 ),
pushTo : function( obj ){
Object.assign( obj, data )
return this
},
then : function( func ){
func( this, data )
return this
},
each : function( callback ){
for( let line of Object.keys( data ) ){
callback( data, line )
}
return this
}
}
}
}
}
//test arraysMode
var hwdt = new csv( "hello,World,5,5" )
.readAsArrays( true )
.then( function( fns, dt ){
console.log( "数据 : " + dt.join( " " ) )
console.log( "JSON : " + fns.json )
} )
.each( function( v, i ){
console.log( "值: " + v + " 位置: " + i )
} )
.result
console.log( hwdt )
//test listMode
var foodList = new csv( `
morning,afternoon,night
rice,water,juice
fish,meat,candy
`.trim() ).readAsList( true )
.then( function( fns ){
console.log( "JSON : " + fns.json )
} )
.each( function( v, i ){
console.log( i + " eat " + v )
} )
.result
console.log( "早上吃 :" + foodList.morning.join( " & " ) ) 非常好帖子,爱来自文主地
页: [1]