UID548063性别保密经验 EP铁粒 粒回帖0主题精华在线时间 小时注册时间2022-8-5最后登录1970-1-1
| - 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[line] ){
- callback( data[line][pos], [ line, pos ] )
- //value index
- }
- }
- return this
- }
- }
- }
- }
- readAsList( backobj=false ){
- let data = ( function( csv ){
- let ret = {}
- for( let key in csv[0] ){
- ret[ csv[0][ key ] ] = []
- for( let line in csv ){
- if( line > 0 ){
- ret[ csv[0][ 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[line] ){
- callback( data[line][pos], [ line, pos ] )
- //value index
- }
- }
- return this
- }
- }
- }
- }
- readAsObject( backobj=false ){
- let data = ( function( csv ){
- let ret = {}
- for( let line in csv ){
- eval( "ret." + csv[line]
- .slice( 0, -1 )
- .join( "." ) + "='" + csv[line]
- .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], 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[0] + " eat " + v )
- } )
- .result
- console.log( "早上吃 : " + foodList.morning.join( " & " ) )
复制代码 |
|