1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| var fs = require('fs');
var reduceCustomer = (output) => output.reduce((output,row)=>{ // 如果沒有值就用空的當預設值,之後push才不會有問題 output[row[0]] = output[row[0]] || []; output[row[0]].push({ 'product':row[1], 'price':row[2], 'amount':row[3] }); return output; }, {});
var funcDoor = (path, fn) => { var rawData = (path) => fs.readFileSync(path, 'utf8') .trim() .split("\n"); // 要傳入參數,否則最後的結果還是function var result = (path)=>fn(rawData(path).map((row) => { return row.split(',') } )); return result(path); }
console.log( funcDoor('data/data.txt', reduceCustomer)); // return; // console.log('output',JSON.stringify(convertJson('data/data.txt'), null, 2));
var reduceCsv = (output) => output.reduce((output, row) => { // 直接整理到一個result的key,之後就不用煩惱怎麼把key移掉 output['result'] = output['result']||[]; let input = { 'id':row[0], 'parent_id':row[1]!='null' ? row[1] : JSON.parse(row[1]) }; output['result'].push(input); // output[i] = input; return output } ,{})['result'] let menuTreeResult; console.log(menuTreeResult = funcDoor('data/menutree.txt', reduceCsv)); fs.writeFile('./data/menutree.json',JSON.stringify(menuTreeResult, null ,2));
|